需要通过 props 或强制组件从 preact/react 中的根组件外部重新加载来传递效果

need to pass an effect via props or force component reload from outside the root component in preact/react

我遇到的情况是组件外部的项目可能会影响后端中的项目。例如:更改其中一个持久属性的值,假设项目状态从“待定”变为“已完成”。

我知道它什么时候发生,但由于它在组件之外,我需要告诉组件它不同步并重新获取数据。但是从外面。我知道你可以通过 props 再次调用 render 方法。但问题是我有一个减速器,状态会选择最后一个状态,如果我使用道具触发效果,我会进入循环。

这是我所做的:

useEffect(() => {
    if (props.effect && !state.effect) { //this runs when the prop changes
      return dispatch({ type: props.effect, });
    }
    if (state.effect) { // but then I get here and then back up and so on
      return ModelEffect[state.effect](state?.data?.item)}, [state.status, state.effect, props.effect,]);

简而言之,因为我无法摆脱道具,所以我得到了第一个,然后是第二个,依此类推,无限循环。

我渲染传递id的根组件:

render(html`<${Panel} id=${id}/>`,
            document.getElementById('Panel'));

然后我的想法是我可以这样做来同步它:

render(html`<${Panel} id=${id} effect="RELOAD"/>`,
                document.getElementById('Panel'));

有更好的方法解决这个问题吗?

非常感谢

我通过将初始化的调度函数传递给全局来解决它。

function Panel (props) {
//...
const [state, dispatch,] = useReducer(RequestReducer, initialData);
//...
useEffect(() => {
//...
window.GlobalDispatch = dispatch;
//...
}, [state.status, state.effect,]);

有了它我可以做到:

window.GlobalDispatch({type:'RELOAD'});