将动态数组从 React 组件导出到另一个组件

Export a dynamic array from a React component to another component

我构建了一个将 Json 文件导入数组以映射结果的 React 组件。我需要在另一个组件中使用该数组。我不知道我是否必须在新组件中构建此组件,或者是否有导出所需数组(数据)的方法。数组源每 4 秒更新一次。

感谢您的帮助。

我的第一个组件是:

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';


class Ramas extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: []
        };
    }

    componentDidMount() {
        const fetchData = () => {
            axios
            .get('http://localhost:8888/dp_8/fuente/procesos_arbol.json')
            .then(({ data })=> {
                this.setState({
                    data: data
                });
                console.log(data);
            })
            .catch(()=> {console.log('no recibido');});
        };
        fetchData();
        this.update = setInterval(fetchData, 4000);
    } //  final componentDidMount


    render() {
        const initialData = this.state.data.map((el) => {
            return (
        <p>id={ el.id } | name - { el.name } | padre - {el.parent}</p>
      );
        });


        return (<div className="datos_iniciales">
      { initialData }
      </div>);
    }

}


ReactDOM.render(
  <Ramas />,
  document.getElementById('container')
);

创建一个可以包含这两个组件的顶级组件。

在 Ramas 组件中 ->

const updatedData = setInterval(fetchData, 4000);
this.props.datasource(updatedData);

编写一个新的顶级组件 ->

class TopComponent Extends React.Component{
  state = {data: ''}

  handleDataUpdate = (updatedData) => {
     this.setState({data: updatedData});
  }

  render = () => {
      <Ramas datasource={this.handleDataUpdate}>
          <SecondComponent updatedData={this.state.data}>
      </Ramas>
  }

}

现在从 SecondComponent updatedData prop 你可以获得新数据

顺便说一句,我写的是ES7语法

如果你有父组件,你应该将它的函数作为 prop 传递给这个组件。 该函数将设置状态,数据将按照 ReactJS 想象的方式流动。

例如,您可以调用而不是 this.setState this.props.jsonToArray 在 jsonToArray 中,您应该调用 setState,它将数据传递给第二个组件。