React Hook "React.useState" 无法在回调中调用。 React Hooks 必须在 React 函数组件中调用

React Hook "React.useState" cannot be called inside a callback. React Hooks must be called in a React function component

我正在尝试根据用户上下文创建默认状态,但我无法在 <myContext.Consumer>{myContext => {}}</myContext.Consumer> 的回调之外使用上下文。当我尝试在回调

中使用 setState 时出现上述错误

这是我的用例:

import * as React from 'react'
import Box from '@mui/material/Box'
import PageTitle from '../01_shared/PageTitle'

import { appCtx } from '../01_shared/appContext'

const MyComponent = () => {

  const [options, setOptions] = React.useState({
    currency: userContext.currency, // <=I need user context information here
  })

  return <appCtx.Consumer>{translationContext => {
    // I cannot use React.useState here
    return (
      <Box>
        <PageTitle>Hello {userCtx.firstName} you have 3 {options.currency}</PageTitle>
      </Box>
    )
  }}</appCtx.Consumer>
};

export default MyComponent

我知道我可以在访问 userContext 后直接设置状态,但这看起来更像是一种变通方法,而不是正确的解决方案。

你能给我指明正确的方向吗?

函数组件可以使用 useContext 钩子来获取上下文值,因此您不需要渲染 <appCtx.Consumer>:

const MyComponent = () => {
  const userContext = React.useContext(appCtx);
  const [options, setOptions] = React.useState({
    currency: userContext.currency,
  });

  return (
    <Box>
      <PageTitle>
        Hello {userContext.firstName} you have 3 {options.currency}
      </PageTitle>
    </Box>
  );
};