gpt4 book ai didi

javascript - React - 在 child 中设置状态?

转载 作者:行者123 更新时间:2023-11-30 14:59:53 25 4
gpt4 key购买 nike

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

我有几个组件。一个是 Gallery,调用 ajax 请求获取值。另一个组件是 InnerContent。它是 Gallery 的子组件。

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

这是我的输入数据:

[
{
"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>
);
}
}

最佳答案

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

在您的案例中,您只需要处理一个条件。您在 constructor 中设置状态,但是当组件第二次呈现并且 props 更改时,状态与 constructor 只被调用一次。

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

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

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

关于javascript - React - 在 child 中设置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711142/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com