我正在尝试编写一个使用 toastr 组件的应用程序。但是,当我尝试在此组件中调度 redux 操作时,我收到以下控制台消息:
警告:在现有状态转换期间无法更新(例如 在
render
或其他组件的构造函数中)。呈现方法 应该是道具和状态的纯函数;构造函数副作用 是反模式,但可以移动到componentWillMount
。
您可以在此代码沙箱中看到一个示例。特别是,问题出在第 23 行的 toastr.js 组件。谢谢!
问题正是错误消息所说的:您直接在 render()
方法中触发了 React 状态更新的形式:
const Toasts = ({ appointments, resetState, toastedAppointment, toasts }) => {
if (toasts.type) {
switch (toasts.type) {
case "dataFetched":
resetState(); // Dispatching this action creates the warning.
在这种情况下,它正在调度一个 Redux 操作,但这最终会导致 React setState()
调用。
不要那样做:) 副作用逻辑,例如根据当前状态触发某种额外的更新,应该发生在类似 componentDidUpdate
. Toasts
组件可能需要相应地从函数组件转换为类组件。