简体   繁体   中英

How to share state between components using Redux?

I have two components, a parent and a child. I want to store the state of the child component using redux and to access it in the parent or from anywhere in the application.

Could someone please help me to solve this problem? Thanks

The question is too broad, but I will give you the general idea of what you need to do.

  • You will need to create a redux action, and dispatch it from inside the child component. Pass the data that you want to store.

  • You will need to create a reducer to handle this action. It should receive the action and save the data in the store. It should return a new copy of the state that includes the added data.

  • You will need to create a store that uses the reducer you created above.

  • You will have a Provider component up in the tree, that uses the store you created above.

  • In your parent component, you can use the connect method from react-redux to access the data you saved in the store, using the mapStateToProps argument of connect .

Feel free to post a more specific question about any of the steps above.

Read more about redux and react-redux:

https://redux.js.org/introduction/core-concepts

https://react-redux.js.org/introduction/quick-start

Following two steps are....

Step 01: set props value by using redux like

jsx:

<button onClick={()=>this.props.AddProductToCart(this.state.quantity)} className='btn btn-sm btn-success'>Add to Cart</button>

const mapStateToProps=(state)=>({
    quantity:state.CartQtyManageReducer.quantity
})

export default connect(mapStateToProps,{AddProductToCart})(AddToCart)

Step 02: get props in LayoutNavbar from redux state

const mapStateToProps=(state)=>({
    quantity:state.CartQtyManageReducer.quantity
})

export default connect(mapStateToProps,{})(LayoutNavbar)

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