【问题标题】:Export a dynamic array from a React component to another component将动态数组从 React 组件导出到另一个组件
【发布时间】:2018-05-18 21:05:57
【问题描述】:

我构建了一个 react 组件,它将 Json 文件导入到数组中以映射结果。我需要在另一个组件中使用该数组。我不知道我是否必须在新组件中构建这个组件,或者是否有一种方法可以导出所需的数组(数据)。数组源每 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')
);

【问题讨论】:

  • 这对你有用吗?您是在问是否有更好的解决方案,或者您是否遇到任何错误?
  • 不,罗迪乌斯。我想在另一个组件中像数据源一样重用该数组。

标签: reactjs export components


【解决方案1】:

制作一个可以包含这两个组件的顶级组件。

在 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 道具获取最新数据

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

【讨论】:

    【解决方案2】:

    如果你有父组件,你应该把它的函数作为一个道具传递给这个组件。 该函数将设置状态,并且数据将以 ReactJS 所想象的方式以一种方式流动。

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

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 2021-07-03
      • 1970-01-01
      • 2021-01-11
      • 2021-01-02
      • 2021-06-17
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      相关资源
      最近更新 更多