无法在无状态组件的现有状态转换期间进行更新

8
我有以下警告:

警告: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。 当用户创建游戏时,我希望通过一个已经在组件大厅的容器初始化时监听的socket.io操作事件,将他重定向到服务器生成的新URL,并将其分配给属性currentGame
然而,由于currentGame属性发生变化,组件被重新渲染,因此该行...
{props.history.push(`/${props.currentGame}[${props.username}]`)}

由于属性currentGame现在已经有了值,并且在重新渲染过程中不应修改history属性,因此会生成警告。

有任何想法如何修复它吗?

谢谢!

2个回答

19

不应该在render中编写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>
    )
}

6
如果您不介意,能否向我解释为什么在渲染中 props.history.push 不起作用? - IAMSTR

1

如果您想在开始时执行某些操作,请将代码放入componentDidMount()中,而不是编写条件并使用history.push()。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接