是否可以更改 useEffect 钩子中的状态变量?

时间:2021-01-12 12:26:17

标签: reactjs

我想使用相同的表单进行添加和更新。从带有按钮单击事件的列表页面中,我设置了 recordForEdit 状态变量并将其传递给表单。这是代码片段:

<RoleForm recordForEdit={recordForEdit} />  

在 RoleForm 页面中,我将其作为道具接收并将其设置在一个对象中。然后在useEffect钩子中想要更新roleState。但它没有用。请帮帮我。

这是我的代码片段:

import React, { useEffect, useState } from 'react';
import { Button, Checkbox, FormControlLabel, Grid, TextField } from '@material-ui/core';
import axios from '../../../../../services/auth/jwt/config'

export default function Roles(props) {
  const [roleState, setRoleState] = useState({
    name: '',
    description: '',
    permissions: []
  });
  const [initialPermissions, setInitialPermissions] = useState({
    viewUser: false,
    manageUser: false
  })

  const { recordForEdit } = props
  useEffect(() => {
    if (recordForEdit != null) {
      let obj = {
        name: recordForEdit.name,
        description: recordForEdit.description,
        permissions: recordForEdit.permissions
      }
      setRoleState({
        name: obj.name,
        description: obj.description,
        permissions: obj.permissions
      })
      console.log(obj);
      console.log(roleState);
    }
  }, [recordForEdit]);

  useEffect(() => {
    checkedPermissions();
  }, [initialPermissions.viewUser, initialPermissions.manageUser]);

  const handleSubmit = () => {
    // axios
    //   .post('api/Account/roles', roleState)
    //   .then(res => {
    //     console.log(res);
    //   })
    //   .catch(err => {
    //     console.log(err);
    //   })
    console.log(roleState);
  }

  let permissions = []
  const checkedPermissions = () => {
    let viewUserCheck = initialPermissions.viewUser;
    let manageUserCheck = initialPermissions.manageUser;
    const viewUserObj = {
      name: "View Users",
      value: "users.view",
      groupName: "User Permissions",
      description: "Permission to view other users account details"
    }
    const manageUserObj = {
      name: "Manage Users",
      value: "users.manage",
      groupName: "User Permissions",
      description: "Permission to create, delete and modify other users account details"
    }
    viewUserCheck
      ? permissions.push(viewUserObj)
      : permissions.filter(item => item != viewUserObj)
    manageUserCheck
      ? permissions.push(manageUserObj)
      : permissions.filter(item => item != manageUserObj)
    setRoleState({ ...roleState, permissions: permissions })
  }

  return (
    <form >
      <Grid container  >
        <Grid item xs={12} sm={6} lg={6} md={6}>
          <TextField
            variant="outlined"
            name='name'
            label="Role Name"
            value={roleState.name}
            onChange={e => { setRoleState({ ...roleState, name: e.target.value }) }}
          />
        </Grid>
        <Grid item xs={12} sm={6} lg={6} md={6}>
          <TextField
            variant="outlined"
            name='description'
            label="Description"
            value={roleState.description}
            onChange={e => { setRoleState({ ...roleState, description: e.target.value }) }}
          />
        </Grid>
        <br />
        <br />
        <Grid container item xs={12}>
          <Grid item xs={12} sm={6} lg={6} md={6}>
            <h3> User Permissions</h3>
            <FormControlLabel
              control={<Checkbox
                checked={initialPermissions.viewUser}
                onChange={e => { setInitialPermissions({ ...initialPermissions, viewUser: e.target.checked }) }} />}
              label="View User"
            />
            <FormControlLabel
              control={<Checkbox
                checked={initialPermissions.manageUser}
                onChange={e => { setInitialPermissions({ ...initialPermissions, manageUser: e.target.checked }) }} />}
              label="Manage User"
            />
          </Grid>
        </Grid>
        <Grid container item xs={12} sm={12} md={12} lg={12} justify='flex-end'>
          <Button variant="contained" color="secondary" onClick={handleSubmit}> Submit</Button>
        </Grid>
      </Grid>
    </form>
  );
}

1 个答案:

答案 0 :(得分:1)

setRoleState 是异步方法,不能在roleState 之后立即获取setRoleState() 的更新值。

  setRoleState({
    name: obj.name,
    description: obj.description,
    permissions: obj.permissions
  })
  console.log(roleState); // This will show the old value of the roleState.

您应该使用 useEffect 并添加一个 roleState 依赖项来检查更新的状态值。

useEffect(() => {
  console.log(roleState);
}, [roleState]);