在反应挂钩中使用以下方法或更新 UI 的任何替代方法是否好
is it good to use following in react hooks or any alternative to update the UI
这是我的代码我面临的问题是 UI 在状态改变后不重新渲染
const [, setRand] = useState()
setRand(Math.random())
您不能将 useState
用作 const [, setRand] = useState()
;
这是来自 ReactJs documentation 的描述。
你需要这样使用它
const [random, setRandom] = useState(0);
//or you can just set random in the beginning like
const [random, setRandom] = useState(Math.random());
并确保您在某处通过 return()
方法访问它,例如:
<p>{ random }</p>
你最好使用 key 属性重新渲染
return (
<SomeOtherComponent>
<Component key={dependencyVariable} />
</SomeOtherComponent>
)
这是我的代码我面临的问题是 UI 在状态改变后不重新渲染
const [, setRand] = useState()
setRand(Math.random())
您不能将 useState
用作 const [, setRand] = useState()
;
这是来自 ReactJs documentation 的描述。
你需要这样使用它
const [random, setRandom] = useState(0);
//or you can just set random in the beginning like
const [random, setRandom] = useState(Math.random());
并确保您在某处通过 return()
方法访问它,例如:
<p>{ random }</p>
你最好使用 key 属性重新渲染
return (
<SomeOtherComponent>
<Component key={dependencyVariable} />
</SomeOtherComponent>
)