反应 - 在孩子中设置状态?

时间:2017-10-12 13:40:00

标签: javascript reactjs

我是Reacts的新手。我看了很多帖子,但找不到解决问题的方法。

我有几个组件。一个是Gallery,在其上调用ajax请求来获取值。另一个组件是InnerContent。它是Gallery的儿童组成部分。

我的问题是在子组件中将状态设置为道具是正确的,在我的情况下(InnerContent)?

这是我的输入数据:

[
      {
        "collection": 1,
        "article": 1,
        "name": "Gallery 2",
        "images": [{
            "id": 2,
            "name": "aaa",
            "src": "http://via.placeholder.com/200x200"
          },
          {
            "id": 3,
            "name": "bbb",
            "src": "http://via.placeholder.com/200x200"
          }
        ]
      }
    ]

这是我的代码:

    class InnerContent extends Component {
  constructor(props){
    super(props);

    this.state = {
      images: this.props.data.images,
    };
  }

 removeImage() {
   /*change state in this Component*/
 }

  render() {
    return (
      <div>
        <div>Gallery name: {this.props.data.name}</div>
        <GalleryImageContent>
          <SortableItem removeImage={this.removeImage} {...this.state} />
        </GalleryImageContent>
      </div>
    );
  }
}

function Content(props) {
  let rows = [];

  props.data.forEach((data) => {
    rows.push(<InnerContent data={data}/>)
  });

  return (
    <div>
      {rows}
    </div>
  );
}

class Foo extends Component {
  constructor(props){
    super(props);

    this.state = {
        data: Service.data
    };
  }

  render() {
    return(
      <div>
        <button onClick={/*change state*/}>Add Gallery</button>
        <Content data={this.state.data}/>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

可以在子组件中将状态设置为props。

你必须在你的情况下再处理一个条件。您在constructor中设置状态,但是当第二次呈现组件并且props更改时,状态保持不变,因为constructor仅被调用一次

基本上,您必须使组件state与道具保持同步。您可以使用componentWillReceiveProps(nextProps)函数来解决此问题。

&#13;
&#13;
componentWillReceiveProps(nextProps) {
  this.setState({
    images: nextProps.data.images
  });
}
&#13;
&#13;
&#13;

如果它能解决您的问题,请告诉我。

相关问题