【问题标题】:Cannot update during an existing state transition in stateless component在无状态组件中的现有状态转换期间无法更新
【发布时间】:2018-08-29 05:51:25
【问题描述】:

我有以下警告:

警告:setState(...):在现有状态转换期间无法更新(例如在 render 或其他组件的构造函数中)。

使用 React-redux-router 我了解,但不知道如何修复。

这是生成警告的组件。

const Lobby = props => {
  console.log("props", props)
  if (!props.currentGame)
    return (
      <div>
        <input type="text" ref={input => (roomName = input)} />
        <button
          className="button"
          onClick={() => {
            props.createRoom(roomName.value)
          }}
        >
          Create a room
        </button>
      </div>
    )
  else
    return (
      <div>
        {props.history.push(`/${props.currentGame}[${props.username}]`)}
      </div>
    )
}

export default Lobby

我在这里所做的是我的组件从 Redux 商店接收 currentGame 属性。此属性初始化为 null。 当用户创建游戏时,我想将他重定向到由服务器生成的新 URL 上,该 URL 我在属性 currentGame 内分配一个 socket.io 动作事件,该事件在组件 Lobby 已初始化。

但是,由于 currentGame 属性发生了变化,组件被重新渲染,因此行

{props.history.push(`/${props.currentGame}[${props.username}]`)}

生成警告,因为属性 currentGame 现在有一个值,并且在重新渲染期间不应修改 history 属性。

关于如何修复它的任何想法?

谢谢!

【问题讨论】:

    标签: javascript reactjs socket.io redux react-router


    【解决方案1】:

    你不应该在渲染中写props.history.push,而是使用Redirect

    const Lobby = props => {
      console.log("props", props)
      if (!props.currentGame)
        return (
          <div>
            <input type="text" ref={input => (roomName = input)} />
            <button
              className="button"
              onClick={() => {
                props.createRoom(roomName.value)
              }}
            >
              Create a room
            </button>
          </div>
        )
      else
        return (
          <div>
            <Redirect to={`/${props.currentGame}[${props.username}]`} />
          </div>
        )
    }
    

    【讨论】:

    • 如果你不介意你能解释一下为什么props.history.push 在渲染中不起作用
    【解决方案2】:

    做一件事,而不是编写条件并使用 history.push() 推送,如果您一开始就尝试这样做,只需将代码放在 componentDidMount() 中。

    componentDidMount(){
     if(condition){
       history.push('/my-url');
     }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2019-04-05
      • 1970-01-01
      • 2017-12-20
      • 2019-08-19
      • 1970-01-01
      相关资源
      最近更新 更多