简体   繁体   中英

How to pass state to more then one component in redux

I start working with React + Redux and newbie to the framework.*

What is am trying to do?

I have to click a button and on the click it will show an svg path in other container/svg tag.

My code or my code

import { connect } from "react-redux";
import { BodyTemplate, Button } from "../component/svgPreview/Preview.jsx";
import { previewBodyTemplate } from "../modcon/Actions.js";

const mapStateToProps = ({ previewTemplateState }) => {
    return ({
        previewTemplateState: previewTemplateState
    });
};

const mapDispatchToProps = (dispatch) => {
    return ({
        onImageClick: (value) => {
            dispatch(previewBodyTemplate(value));
        }
    });
};

/*  the following code will work because we cannot export more then one by
default **/

/*
const PreviewContainer = connect(mapStateToProps, mapDispatchToProps)(Button);
const PreviewBody = connect(mapStateToProps, mapDispatchToProps)(BodyTemplate);
export default PreviewContainer;
export default PreviewBody;

*/


/* so i try this */

export const PreviewContainer = connect(mapStateToProps, mapDispatchToProps)(Button);
export const PreviewBody = connect(mapStateToProps)(BodyTemplate);

According to my knowlage i am passing the state to two components so when the state of one update it will update the other.

But the file is not working because we and not export it directly.

How i have to tackle to pass the state to more then one components

below is the error when i am exporting directly

在此处输入图片说明 *

You need to create a parent component, this component will contain the button and the preview component.

const MyContainer = ({ image, onImageClick }) => (
  <div>
    <div className="sidebar">
      <Button label="Preview image" onClick={onImageClick} />
    </div>
    <div className="content">
      <Preview source={image} />
    </div>
  </div>
);

Once you have your container ready, you need to map the props of this component to the state/actions from redux.

const mapStateToProps = ({ image, previewTemplateState }) => {
  return ({
    image: image,
    previewTemplateState: previewTemplateState
  });
};

const mapDispatchToProps = (dispatch) => {
  return ({
    onImageClick: (value) => {
        dispatch(previewBodyTemplate(value));
    }
  });
};

export default connect(mapStateToProps, mapDispatchToProps)(MyContainer);

Now the main container will receive the data and the actions, from there you can send whatever you need to the children components.

The button and the preview image component are stateless component, they just receive props from the parent container.

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