reactjs 如何能够更新redux状态所在的输入字段

68de4m5k  于 2023-06-29  发布在  React
关注(0)|答案(1)|浏览(111)

我有一个列出记录的表,并有一些最小的功能来更新数据。该表呈现如下:

const renderTableRows = () => {
    return invoices?.map((invoice, i) => (
      <tr
        key={i}
        onClick={() => handleClick(invoice.ID)}
        className={`${InvoiceStatus_Category(invoice.Status)}`}
      >
        <td>
          <span className={`${InvoiceStatus(invoice.DaysFromDueDate)}`}>O</span>
        </td>
        {/* <td className="choice">{invoice.BillToName}</td>
        <td className="choice">{invoice.InvoiceNumber}</td>
        <td className="choice">{invoice.OFFC}</td> */}
        <td>
          <select
            name="status"
            onChange={(e) => handleStatusOnChange(e, invoice.ID)}
            value={invoice.Status}
            placeholder="Change Status"
          >
            <option value={invoiceStatus}></option>
            <option value="Paid">Paid</option>
            <option value="Post&Hold">Post&Hold</option>
            <option value="Instructions">Instructions</option>
          </select>
        </td>
        <td className="choice">
          <input
            key={i}
            className="matter-input"
            name="matterInput"
            type="text"
            onChange={onChange}
            maxLength={6}
            value={invoice.MatterNo}
          />
        </td>
        <td>
          <button
            className="matter-button"
            onClick={() => {
              buttonOnClick(invoice.ID, matter);
              setMatter("");
            }}
          >
            Add Matter
          </button>
        </td>
      </tr>
    ));
  };

状态被正确地填充,但是我不能在输入字段中键入。是否可以在此字段中键入?onChange事件如下:
const onChange = (e, i) => { const { name, value } = e.target; setMatter(value); };
我甚至试过useRef,但没有成功。
然后onclick按钮更新API。请参见下文:

const buttonOnClick = (i, mat) => {
if (mat > 0) {
  axios({
    method: "put",
    url: "http://localhost:64198/api/UpdateMatter",
    data: {
      InvoiceID: i,
      Matter: mat,
    },
    headers: { "Content-Type": "application/json" },
  }).then((res) => {
    dispatch(fetchAsyncInvoices());
    setMatter("");
  });
  setMatter("");
  window.location.reload(false);
}

};
我想在突出显示的输入框中键入新值x1c 0d1x

8aqjt8rx

8aqjt8rx1#

你不想每次输入时都更新redux状态,你必须创建一个useState钩子并将其绑定到你的redux状态,然后只有当你需要执行一个操作时才更新后者:

const [invoicesState, setInvoicesState] = useState([]);
useEffect(() => {
 setInvoicesState(invoices)
},[invoices])

现在,要通过invoices进行Map,则需要通过invoicesState进行Map。
onChange函数应该看起来像这样:

const onChange = (e, id) => {
  const { value } = e.target;
  setMatter(value);
  setInvoices(prev => prev.map(invoice => {
    if(invoice.ID === id){
      return {
        ...invoice, MatterNo: value
      }
    } else{
      return invoice
    }
  }))
};

所以你必须把发票的id传递给函数来更新它

<input
  onChange={() => { onChange(e,invoice.ID) }}
/>

当你点击按钮更新任何东西时,你只需要更新你的redux状态,而不是本地状态

相关问题