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 };...

问题:

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. My goal is to have state as an array of objects.


回答1:

I assume you want to concatenate newProps.course.courses.data to 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),
        });
    }
}
  • 发表于 2018-12-30 02:43
  • 阅读 ( 202 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除