2017-10-12 99 views
1

我是新来的反应。我读了很多帖子,找不到解决我的问题的方法。反应 - 在儿童中设置状态?

我有几个组件。一个是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

你的问题是什么?是的,您可以将道具分配到您的孩子组件的状态 – Jeffin

+2

如果您创建了问题的简化版本,而不是让我们深入了解您的代码,这将有所帮助。我假设你正试图改变你的父组件的状态。如果是这样,创建一个更改状态的函数,即'updateField =(newVal)=> this.setState({field:newVal});'并通过道具传递给你的子组件,然后像这样调用它'this .props.updateField(VAL);' – fungusanthrax

回答

2

这是正常设置状态作为子组件的道具。

你必须在你的情况下照顾一个更多的条件。您将状态设置为constructor,但当组件第二次呈现并且props发生更改时,状态将保持不变,因为constructor只会被调用一次。

基本上,你必须保持组件的state与道具最新。你可以使用componentWillReceiveProps(nextProps)函数来解决这个问题。

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

让我知道这是否解决您的问题。