简体   繁体   English

如何在 redux 状态更改时渲染 React 组件?

[英]How to render a React component on redux state change?

I am using this redux-socket.io middleware to dispatch actions from the server on socket.io requests.我正在使用这个redux-socket.io中间件在 socket.io 请求上从服务器分派动作。 This part works fine, all the stuff I needed until now, I could do with this.这部分工作正常,到目前为止我需要的所有东西,我可以用这个来做。

Now I am trying to use this middleware to dispatch an action that sets a piece of state, then I would like to render a React component (basically a floating window, above everything else) when the state contains a specific key.现在我正在尝试使用这个中间件来调度一个设置一个状态的动作,然后我想在状态包含一个特定的键时渲染一个 React 组件(基本上是一个浮动窗口,高于一切)。

The problem is, after dispatching the action, I am not sure how to make React render a component on state change.问题是,在分派动作后,我不确定如何让 React 在状态更改时呈现组件。 (Above the currently rendered component) (在当前渲染的组件之上)

Since I want to render this component above everything else, I don't think it would be a good idea to check for updated props in every single component I have.由于我想将此组件呈现在其他一切之上,因此我认为检查我拥有的每个组件中是否有更新的 props 不是一个好主意。

I thought about using the subscribe API but I haven't found any examples of rendering a component from inside there.我考虑过使用订阅 API,但我还没有找到任何从内部渲染组件的示例。

What would be the best solution here?这里最好的解决方案是什么?

You can check the state in your return for the render with something like a ternary operator and if true, then render the popup.您可以使用三元运算符之类的东西检查渲染返回中的状态,如果为真,则渲染弹出窗口。

{state === correct ? <PopUp/> : null}

Every time state changes, the page is dynamically re-rendered.每次状态改变时,页面都会动态重新渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM