通过react-redux分发组件

问题描述

我想传递一个组件,并通过redux将其显示在另一个组件中。 我正在做这样的事情:

ComponentTodispatch.js

const ComponentTodispatch = (props) => {
    return (<div>Propagate me {props.anthem}</div> {/* props.anthem = undefined,unlike what I expect.*/}
);
};
export {ComponentTodispatch};

在以下组件中,我有一个分派以前定义的按钮。

BruitEvent.js

 // code above
`import {ComponentTodispatch} from "./ComponentTodispatch";
 import {showComponentAction} from "./actions";
 const BruitEvent =()=>{
    const dispatch = usedispatch();
    return (<button onClick={(evt)=>dispatch(showComponentAction(ComponentTodispatch)}>
 Click to dispatch</button>);
 };`

触发此事件的动作是: actions.js

 `
 export function ShowComponentAction(Component) {

 return {
    type: SHOW_ACTION,payload: {
      component: <Component />,},};
}`

最后,我可以显示传播的组件:

const dispayComponent = () =>{
const { component} = useSelector((state) => {
if (state.testdisplay) {
  return {
    component: state.testdisplay.component,};
}
   return { component: null };
 });

useInjectReducer({ key: "testdisplay",reducer });

   return (<div>{component}</div>);
 }
 export {displayComponent};

到目前为止,非常好,多亏了David Hellsing for his insight,我可以显示每个静态的东西都驻留在`ComponentTodispatch'中,但是它无法处理道具。

问题:在调度组件本身时如何发送道具?

解决方法

您需要在分派组件之前实例化并封装道具 ,或者在分派的动作中传递未实例化的组件和props对象,然后将道具传递给接收端的组件。我建议后者,同时发送组件和道具。

const BruitEvent =()=>{
  const dispatch = useDispatch();
  return (
    <button
      onClick={(evt) => dispatch(
        showComponentAction(ComponentToDispatch,/* some possible props object */)
      )}
    >
      Click to dispatch
    </button>
  );
};

...

export function ShowComponentAction(Component,props = {}) {
  return {
    type: SHOW_ACTION,payload: { Component,props },// <-- assumes reducer places in state.testDisplay
  },};

...

const DispayComponent = () =>{
  const { Component,prop } = useSelector((state) => state.testDisplay);

  useInjectReducer({ key: "testDisplay",reducer });

  return Component ? <div><Component {...props} /></div> : null;
}