用于创建或编辑用户的组件

下面代码的一部分,我在其中将isActive状态有条件地设置在useEffect

我正在获取user_data的其他字段,并成功更新了state 但只有setIsActive人没有更新state

function CreateUser() {

    const [isActive, setIsActive] = useState<boolean | undefined>();
    
    useEffect(() => {
        if (params_user_id?.id != null) {
            const SINGLE_USER_URL = `users/${params_user_id.id}/edit`;
            const getSingleUser = async () => {
                const {data} = await axios.get(SINGLE_USER_URL)
                console.log(data)
                setIsActive(data.isactive)
                console.log('isactive', isActive)
            }
            getSingleUser();
        }
    }, [params_user_id])

    return (
        <>
     <Form.Check
          defaultChecked={isActive}
          className='mb-3'
          type='checkbox'
          id='active'
          onChange={e => setIsActive(!(isActive))}
          label='Active: Unselect for deleting accounts.'/> 
        </>
    )

}

Form.Check个从Bootstrap-React

When I hit the Edit page

Screen Shot of result page

我确实try 了很多东西,比如ternary operatorcheckBox不是checked,因为它是undefined

推荐答案

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

这就是为什么我们有useEffect,这是一个内置的react 挂钩,当它的一个依赖项发生变化时激活回调.

在您的例子中,您已经使用useEffect来更新状态,但是如果您想对状态更改采取行动,或者只是记录它的值,那么您可以使用另一个单独的useEffect来实现该目的.

Example:

useEffect(() => {
   console.log(isActive)
   // Whatever else we want to do after the state has been updated.
}, [isActive])

只有在完成状态更改并进行渲染后,此console.log才会运行.

  • 注意:本例中的"isActive"可以与您正在处理的任何其他状态部分互换.

有关这方面的更多信息,请查看documentation.


其他 comments :

  • Best to avoid using the loose != to check for equality/inequality and opt for strict inequality check instead, i.e. - !==
    Loose inequality is seldom used, if ever, and could be a source for potential bugs.

  • Perhaps it would better to avoid typing this as boolean | undefined.
    Unless justified, this sounds like another potential source for bugs.
    I would suggest relying on just boolean instead.

Reactjs相关问答推荐

无法覆盖MUI工具栏上的左右填充,除非使用!重要

Inbox Enum类型以React组件状态时出现TypScript错误

NextJs Form不允许我输入任何输入,

获取未捕获的错误:Gatsby生产版本上的最小化react 错误#418

如何使用.Aggregate从多个集合中获取数据,包括使用Mongoose+NextJS的SUM值

React,当我调用handleSubmit()函数时,我正在将application/json和multiform/data中的数据发送到后端,但student_image中没有数据:null

Github 操作失败:发布 NPM 包

如何使用 React 获取表单中的所有值?

React 无效的钩子调用:如何避免嵌套钩子?

无法从子组件传递数据到父组件

如何修改 react/jsx-no-useless-fragment 规则以允许 <>{children}

Zod 验证模式根据另一个数组字段使字段成为必需字段

如何到达类组件中的状态?

Formik onChange() 字段挂钩覆盖显示值和 Select 机制

在 React 中使用复选框管理状态

使用 React.lazy 调试 webpack 代码拆分

React Final Form - 单选按钮在 FieldArray 中不起作用

如何将值从下拉列表传递到 select 上的输入?响应式JS

使用 yarn 编译 protobuf js 时出现错误pbjs: command not found

axios post方法中的请求失败,状态码为500错误