【问题标题】:React not rendering after update state object更新状态对象后反应不渲染
【发布时间】:2021-05-17 16:05:52
【问题描述】:

我在更改 select 的值后更新了我的状态对象。它为对象设置了正确的值,但没有在浏览器中更新(输入字段)。

import React, { useState, useEffect } from 'react';
import { Controller, useForm } from "react-hook-form";
import { Button, Form, Label, Input, Alert } from 'reactstrap';
import NumberFormat from 'react-number-format';
// More imports

const AddUser = (props) => {
   const propID = props.propID;

   // The object has more properties. I'm just showing the ones related to the issue
   const [ addUser, setAddUer ] = useState({
      unitID: 0,
      adminFee: 0
   });
   const [ units, setUnits ] = useState([]);

   useEffect(() => {
      async function fetchData() {
         // this method is an axios request to grab data
         const data = await myAxios.getUnits(propID);
         setUnits(data);
      }
      fetchData();
   }, [propID]);

   const handleUnitChange = async (id) => {
      const unitCharges = await myAxios.getUnitCharges(parseInt(id));
      if(unitCharges !== null) {
         setAddUer ({
            ...addUser,
            unitID: id,
            adminFee: parseFloat(unitCharges.AdminFee).toFixed(2)
         });
       }
   }
   
   // There is a lot of other fields and style here.
   // I'm showing just the related fields
   return (
      <>
         <Label for="unit" className="mr-sm-10">Unit</Label>
         <Input type="select" name="unit" id="unit" 
            value={addUser.unitID} onChange={(e) => handleUnitChange(e.target.value)}
            innerRef={register({ required: true })}
         >
            <option value="0">Select</option>
            {units.map((obj) => {
               return (
                  <option 
                      key={obj.UnitID} 
                      value={obj.UnitID}
                  >
                     {obj.UnitName}
                  </option>
               );
           })}
         </Input>
        <Label for="admin" className="mr-sm-10">Admin</Label>
        <Controller
            as={
                <NumberFormat
                    thousandSeparator={true}
                    prefix={"$"}
                    onValueChange={(v) => {
                        setAddUer({...addUser, adminFee: v.floatValue === undefined ? 0 : v.floatValue})
                    }}
                />
            }
            name="admin"
            id="admin"
            variant="outlined"
            defaultValue={addUser.adminFee}
            getInputRef={register({ required: true })} 
            control={control}
            className="form-control"
        />
      </>
   );
};

export default AddUser;

沙盒用数组代替 Axios 请求:https://codesandbox.io/s/weathered-star-3i9u4?file=/src/App.js

【问题讨论】:

标签: reactjs


【解决方案1】:

请尝试用以下代码替换您代码中的控制器部分。

      <Controller
        name="admin"
        id="admin"
        variant="outlined"
        getInputRef={register({ required: true })}
        control={control}
        className="form-control"
        value={addUser.adminFee}
        render={({ field }) => (
          <NumberFormat
            thousandSeparator={true}
            prefix={"$"}
            value={addUser.adminFee}
            onValueChange={(v) => {
              setAddUer({
                ...addUser,
                adminFee: v.floatValue === undefined ? 0 : v.floatValue
              });
            }}
          />
        )}
      />

【讨论】:

  • 有效!谢谢你。你介意解释一下原因吗?
  • 为了让一个 React 组件可控,你必须给组件设置 value props,但是你之前的代码中没有指定它。
  • 知道了!再次感谢您
猜你喜欢
  • 2022-07-12
  • 2020-01-13
  • 2021-01-27
  • 1970-01-01
  • 2017-03-24
  • 1970-01-01
  • 1970-01-01
  • 2020-10-07
  • 2017-12-23
相关资源
最近更新 更多