我将selectedProduct
移至Products
组件。然后,我向属性selectedProduct
添加了新值。如何将此对象返回到App
数组的组件products
?
应用
class App extends Component {
constructor(){
super();
this.state {
products: [
{
color: ['black', 'orange']
desc: 'gfgfg'
},
{
color: ['yellow'],
desc: 'gfgfgfg'
}
]
}
}
add = (updateProduct) => {
const {products} = this.state;
this.setState({
products: [...products, updateProduct]
})
}
render () {
let selectedProduct = this.state.products[0];
return (
<div>
<ul>
{
this.state.products
.map((product, index) =>
<Product
key={index}
index={index}
product={product}
/>
)
}
</ul>
<Products
selectedProduct = {selectedProduct}
add={this.add}
/>
</div>
)
}
}
export default App;
产品
class Products extends Component {
constructor(){
super();
this.state = {
selectProduct: [{
color: ['black', 'orange', 'pink]
desc: 'gfgfg'
}]
}
}
componentDidUpdate (prevProps) {
if (prevProps.selectedProduct !== this.props.selectedProduct) {
this.setState({
selectProduct: this.props.selectedProduct
});
if (this.props.add) {
this.props.add(this.state.selectProduct)
}
}
}
render () {
return (
<div>
</div>
)
}
}
答案 0 :(得分:1)
您需要将更改传播回App,在这种情况下,您可以在父组件中设置changeState
函数并将其作为属性向下传播。有关更多信息,请参见此处How to update parent's state in React?
有多个选项,不过我还是建议使用钩子和Context API,例如:https://upmostly.com/tutorials/how-to-use-the-usecontext-hook-in-react/