简体   繁体   English

更新component中的状态将收到Props,其中state是一个数组

[英]updating the state in componentwillreceive Props where state is an array

I have an array as a state . 我有一个数组作为状态。

let coursedata=[];
class XYZ extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      coursedata
    };
  }

  componentWillReceiveProps(newProps) {
    if (newProps.course.courses.data) {
      const newstate = [
        ...this.state.coursedata,
        newProps.courses.courses.data
      ];
      this.setState({
       coursedata: newstate
    });
  }
}

Please not that newProps.course.courses.data is an array of objects. 请不要newProps.course.courses.data是对象数组。 My goal is to have state as an array of objects. 我的目标是将状态作为对象数组。

I assume you want to concatenate newProps.course.courses.data to state.courseData. 我假设您想将newProps.course.courses.data连接到state.courseData。 If that is the case, simple solution would be: 如果是这样,简单的解决方案将是:

componentWillReceiveProps(newProps) {
    const {courseData} = this.state;
    if(newProps.course.courses.data) {
        return this.setState({
            courseData: courseData.concat(newProps.course.courses.data),
        });
    }
}

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

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