简体   繁体   中英

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. 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

Parent --this.state.hideCart--> Child 2 --coverCart = this.props.hideCart--

But the value in Child 2 never updates properly, and I can't figure out why.

      /*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. 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. Hope it helps!.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM