[英]Passing an updated state value from Parent to Child. React Typescript
I am kind of new to React Typescript, and I want to pass some data from a parent to a child.我是 React Typescript 的新手,我想将一些数据从父级传递给子级。 So basicly whenever the user clicks on an specific element, then it activates a function in the parents component.所以基本上每当用户点击一个特定的元素时,它就会激活父组件中的一个功能。 When that function runs, it changes the value of an boolean to it's oppostite which works fine.当该函数运行时,它会将布尔值更改为与之相反的值,这可以正常工作。 And then It should pass the value to another child.然后它应该将值传递给另一个孩子。 However for some reason, the value that is passed from the parent to the child never changes.但是由于某种原因,从父级传递给子级的值永远不会改变。 It should work like this:它应该像这样工作:
Child 1 --activateFunction---> Parent --runFunction--> this.state.hideCart = false/true子 1 --activateFunction---> 父 --runFunction--> this.state.hideCart = false/true
Parent --this.state.hideCart--> Child 2 --coverCart = this.props.hideCart--父级 --this.state.hideCart--> 子级 2 --coverCart = this.props.hideCart--
But the value in Child 2 never updates properly, and I can't figure out why.但是 Child 2 中的值永远不会正确更新,我不知道为什么。
/*CHILD 1*/
export default class Navbar extends Component <{handleCart:any}> {
render() {
return (
<div style={navbar}>
<h1>Navbar</h1>
<h4 onClick={() => this.props.handleCart()}>Shopping Cart</h4>
</div>
)
}
}
/*PARENT*/
export default class Layout extends Component <{fixCart?:boolean}> {
state = {
hideCart: true
}
render() {
return (
<div style={layout}>
<Navbar handleCart={this.displayCart} />
<Counters fixCart={this.state.hideCart} />
<Content />
<Footer />
</div>
)
}
displayCart = () => {
if (this.state.hideCart == true) {
this.setState({hideCart: false})
}
else {
this.setState({hideCart: true})
}
console.log(this.state.hideCart);
}
}
/*CHILD 2*/
export default class Counters extends Component <{fixCart:any},State>{
state = {
counters: [
{ id: "vegetables", value: 1},
],
hideCart: this.props.fixCart
}
}
The method that you have used leaves the user, as well as code reviewers, confused.您使用的方法让用户和代码审查者感到困惑。 To solve these kinds of data passing functionalities, React-Redux is introduced.为了解决这些类型的数据传递功能,引入了React-Redux 。 Maintain the state variable globally and you would be able to access from anywhere.全局维护状态变量,您就可以从任何地方访问。
And BTW, try checking the values for props that you receive in the child components.顺便说一句,请尝试检查您在子组件中收到的道具的值。 I would suggest you to better use React-Redux-Store.我建议你更好地使用 React-Redux-Store。 Hope it helps!.希望能帮助到你!。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.