【问题标题】:Dispatching components via react-redux通过 react-redux 调度组件
【发布时间】:2021-01-28 08:04:42
【问题描述】:

我想通过 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>);
 };`

触发此事件的动作是: 动作.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。

问题:如何在 dispatch 组件的同时传递 props?

【问题讨论】:

    标签: reactjs redux react-redux react-boilerplate


    【解决方案1】:

    您需要在在组件被调度之前实例化和封装 props,或者在调度的动作中传递未实例化的组件和 props 对象并将 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;
    }
    

    【讨论】:

    • 我在分派之前去实例化组件,但这不是我想要的方法。你的第二个建议正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2016-06-06
    • 2017-08-15
    • 2017-09-26
    • 2020-10-12
    • 2017-04-03
    • 1970-01-01
    相关资源
    最近更新 更多