如何在第一次渲染时使用react钩子更新状态变量

时间:2020-09-03 21:10:29

标签: reactjs react-hooks

我有一个React组件:

const ProjectFamiliesFilterInput = React.memo(({ familyOptions, analysisGroupOptions, projectAnalysisGroupsByGuid, value, onChange, ...props }) => {
  const allFamiliesSelected = !value.familyGuids || value.familyGuids.length === familyOptions.length

...
...

return (
    <Form.Group inline widths="equal">
      <BooleanCheckbox
        {...props}
        value={allFamiliesSelected}
        onChange={selectAllFamilies}
        width={5}
        label="Include All Families"
      />
    </Form.Group>
)
})

我希望根据是否使用allFamiliesSelected在第一次安装时设置value.familyGuids.length > 0。如何通过react hooks实现这一目标?

说明:

allFamiliesSelected = value.familyGuids.length === 0-需要在第一次安装时完成,但是allFamiliesSelected = !value.familyGuids || value.familyGuids.length === familyOptions.length-需要进行后续更新,而不是第一次安装。

3 个答案:

答案 0 :(得分:0)

要在渲染器上初始化钩子,您需要在使用useState初始化钩子时传递该值

const [allFamiliesSelected, updateAllFamiliesSelected ] = useState(!value.familyGuids || value.familyGuids.length === familyOptions.length)

答案 1 :(得分:0)

我认为我可以使用以下代码解决此问题:

const [ allFamiliesSelected, updateAllFamiliesSelected ] = useState(value.familyGuids.length === 0)
           
  const firstUpdate = useRef(true)
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }      
    console.log(value)
    updateAllFamiliesSelected(!value.familyGuids || value.familyGuids.length === familyOptions.length)
  })

以下线程为我提供了几乎完整的解决方案:Make React useEffect hook not run on initial render

我遇到了另一个问题,尽管我将其发布为单独的主题:Redux-form: update syncErrors cause form to skip modifications

答案 2 :(得分:-1)

您必须使用useState();

function ExampleWithManyStates() {
  // Declara várias variáveis de state!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

https://pt-br.reactjs.org/docs/hooks-overview.html