【问题标题】:Updating state as an array of objects将状态更新为对象数组
【发布时间】:2021-06-30 23:44:25
【问题描述】:

所以我一直在尝试设置变量 domainRecordsInput 的值,因为它们是动态的。有时有一两行数据,有时有六八行。我需要更新数组中正确对象中的特定字段。

据我所知:

  function DomainRecordsTable() {
    const [records, setRecords] = useState(['']);

    const { loading, error, data } = useQuery(GET_DOMAIN_RECORDS, {
      variables: {
        domain: domain,
      },
    });

    useEffect(() => {
      if (data && data.getDomainRecords) {
        setRecords( data.getDomainRecords.host );
      }
    }, [data]);

    const [exeRecords] = useMutation(SET_DOMAIN_RECORDS, {
      variables: {
        domain: domain,
        domainRecordsInput: [{
          hostName: "lol",
          recordType: "lol",
          address: "lol",
          mxPref: "lol",
          ttl: "lol",
        }]
      },
    });

    if (loading) return <LoadingIndicator />;
    if (error) return `Error! ${error.message}`;

    return (
      <>

      <TableComp>
        <Table.Head>
          <Table.Row>
            <Table.Cell>
              <span>type</span>
            </Table.Cell>
            <Table.Cell>
              <span>address</span>
            </Table.Cell>
            <Table.Cell>
              <span>value</span>
            </Table.Cell>
            <Table.Cell>
              <span>priority</span>
            </Table.Cell>
            <Table.Cell>
              <span>ttl</span>
            </Table.Cell>
            <Table.Cell>
              <span>actions</span>
            </Table.Cell>
          </Table.Row>
        </Table.Head>

        <Table.Body>
          {data.getDomainRecords.host.map((e, i) => (
            <Table.Row key={i}>
              <Table.Cell>
                <EasyEdit
                  type="text"
                  value={e.type}
                  onSave={(value) => setRecords((records) => ({ ...records[i], type: value }))}
                />
              </Table.Cell>
              <Table.Cell>
                <EasyEdit
                  type="text"
                  value={e.address}
                  onSave={(value) => setRecords((records) => ({ ...records[i], address: value }))}
                />
              </Table.Cell>
              <Table.Cell truncate={true} align="left">
                <EasyEdit
                  type="text"
                  value={e.name}
                  onSave={(value) => setRecords((records) => ({ ...records[i], name: value }))}
                />
              </Table.Cell>
              {e.type === "MX" ? (
                <Table.Cell align="right">
                  <EasyEdit
                    type="text"
                    value={e.mxPref}
                    onSave={(value) => setRecords((records) => ({ ...records[i], mxPref: value }))}
                  />
                </Table.Cell>
              ) : (
                <Table.Cell></Table.Cell>
              )}
              <Table.Cell>
                <EasyEdit
                  type="text"
                  value={e.ttl}
                  onSave={(value) => setRecords((records) => ({ ...records[i], ttl: value }))}
                />
              </Table.Cell>
              <Table.Cell>
                <button>delete row</button>
              </Table.Cell>
            </Table.Row>
          ))}
        </Table.Body>
      </TableComp>

      <button>add row</button>

      </>
    );
  }

【问题讨论】:

    标签: javascript arrays reactjs react-hooks


    【解决方案1】:

    您可以将useState 与对象一起使用。

    注意:未经测试,但类似这样

    const [records, setRecords] = useState({
              hostName: "",
              recordType: "",
              address: "",
              mxPref: "",
              ttl: "",
            });
    
    ...
    
    onSave={() => setRecords(records => ({...records, hostName: e.target.value}))
    

    如果需要数组,使用Object.keys(records)Object.values(records)进行转换。

    【讨论】:

    • @gfylol 你的意思是当你编辑type然后name,那么type将被name替换?
    • 可能是因为在[0] 中设置不正确,似乎record 没有更新。你能console.log确保每个字段设置正确吗?
    【解决方案2】:

    所以这就是我发现对我有用的东西:

    const [records, setRecords] = useState([""]);
    
    useEffect(() => {
      if (data && data.getDomainRecords) {
        setRecords(data.getDomainRecords.host);
      }
    }, [data]);
    
    const updateItem = (prop, event, index) => {
      const old = records[index];
      const updated = { ...old, [prop]: event };
      const clone = [...records];
      clone[index] = updated;
      setRecords(clone);
    };
    
    const [exeRecords, { data: datalol }] = useMutation(SET_DOMAIN_RECORDS, {
      variables: {
        domain: domain,
        domainRecordInput: records.flatMap((e) => [
          {
            hostName: e.name,
            recordType: e.type,
            address: e.address,
            mxPref: e.mxPref,
            ttl: e.ttl,
          },
        ]),
      },
    });
    
    ...
    
    onSave={(e) => updateItem("ttl", e, i)}
    

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 2022-01-06
      • 2016-10-06
      • 2018-07-01
      • 1970-01-01
      • 2021-12-26
      • 2020-05-26
      • 2020-10-21
      • 1970-01-01
      相关资源
      最近更新 更多