How can I dispatch from child components in React Redux?

前端 未结 2 766
逝去的感伤
逝去的感伤 2021-02-08 02:37

My server has code like this:

<

2条回答
  •  情话喂你
    2021-02-08 03:21

    You're getting too caught up on children components. You should structure your app so that you have connected components and non-connected components. Non-connected components should be stateless, pure functions essentially, that take in all their requirements via props. Connected components should use the connect function to map redux state to props and redux dispatcher to props, and then be responsible for passing those props to child components.

    You might have lots of connected components in an app, and lots of non-connected components. This post (by the creator of redux) discusses it in more detail, and talks about non-connected (dumb) components being responsible for actual display of UI, and connected (smart) components being responsible for composing non-connected components.

    An example might be (using some newer syntax):

    class Image extends React {
      render() {
        return (
          

    {this.props.name}

    ); } } class ImageList extends React { render() { return ( this.props.images.map(i => ) ); } } const mapStateToProps = (state) => { return { images: state.images, }; }; const mapDispatchToProps = (dispatch) => { return { updateImage: () => dispatch(updateImageAction()), }; }; export default connect(mapStateToProps, mapDispatchToProps)(ImageList);

    In this example, ImageList is a connected component and Image is a non-connected component.

提交回复
热议问题