繁体   English   中英

在React中将状态数据从父级更改为子级后,如何获取状态数据?

[英]How to get state data right after changing them from parent to child in React?

我有以下几个组件的应用程序。 我有两个子组件(卡和模式)和一个父组件(板)。 只需单击卡组件中的卡,然后将卡ID发送到板组件即可。 电路板组件具有API数据。 它使用来自卡组件的卡ID过滤API数据,并以模式组件显示相关数据。

问题是,模态组件甚至在单击卡之前就在开始时加载一个空数组,即projectData。 然后,我无法获取数组内的任何元素,并为每个数组调用说“无法获取未定义的属性”。

卡组成:

class TaskItem extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      more_state: false
    }
  }

  render() {

    const { sendCardId } = this.props;

    return(
      <div onClick={() => sendCardId(task.projectID)}>
      </div>
    )
  }
}

董事会组成:

class Taskboard extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentID: null,
      projectAllData: [],
      open: false,
    };
  }

  getPojectId = (projectId) => {
    this.setState({
      open: true,
      currentId: projectId
    });

    API.get('project/' + projectId)
      .then(({ data }) => {
        this.setState({
          projectAllData: data.response
        });
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      })
  }

  render(){
    return(
      <ProjectModal
          handleOpen={this.state.open}
          handleClosed={this.handleClose}
          projectID={this.state.currentId}
          projectData={this.state.projectAllData}
        />

      <Column
        key={key}
        index={index}
        title={key}
        tasks={columns[key]}
        getCardId={this.getPojectId}
       />
    )
  }
}

模态成分:

class ProjectModal extends Component {
    constructor(props) {
        super(props);
        this.state = {
            status: 'To do',
        };
    }

    render(){

      const { handleOpen, handleClosed, projectData, projectID } = this.props;
      return(
         <div>{projectData.projectName}</div
      )
    }
}

一次使用setState。

getPojectId = (projectId) => {
    API.get('project/' + projectId)
      .then(({ data }) => {
        this.setState({
          projectAllData: data.response,
          open: true,
          currentId: projectId
        });
      })
      .catch((err) => {
        console.log("AXIOS ERROR: ", err);
      })
  }

并设置初始化状态对象而不是数组

this.state = {
      currentID: null,
      projectAllData: {projectName: ''},
      open: false,
    };

或者这可能更好。

this.state = {
  currentID: null,
  projectAllData: undefined,
  open: false,
};
render(){
  return(
    <>
    {
      this.state.projectAllData && (
        <ProjectModal
          handleOpen={this.state.open}
          handleClosed={this.handleClose}
          projectID={this.state.currentId}
          projectData={this.state.projectAllData}
        />
      )
    }

    <Column
      key={key}
      index={index}
      title={key}
      tasks={columns[key]}
      getCardId={this.getPojectId}
      />
    </>
  )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM