如何解决通过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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。