在react hooks中使用following或更新UI的其他方法是否好

时间:2019-12-06 11:26:22

标签: reactjs react-hooks setstate

这是我的代码,我面临的问题是状态更改后UI无法重新呈现

const [, setRand] = useState()
setRand(Math.random())

2 个答案:

答案 0 :(得分:1)

您不能将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>

答案 1 :(得分:0)

最好使用 key 属性进行重新渲染

return (
  <SomeOtherComponent>
    <Component key={dependencyVariable} />
  </SomeOtherComponent>
)