【问题标题】:React.js: Assign value from state directly to TextFieldReact.js:将值从状态直接分配给 TextField
【发布时间】:2021-01-03 05:23:25
【问题描述】:

我有一个 axios 请求以获取交易的详细信息

getTransaction(batchRef) {
    return axios.post(`${API_BASE_URL_GET_OUTWARD_TRANSACTION}`, {
      batchRef: batchRef,
    });
  }

我通过这个服务调用它:

const [viewOutward, setViewOutward] = useState([]);

OutwardService.getTransaction(rowData.batchRef).then((response) => {
    setViewOutward(response.data);
});

像这样在 viewOutward 状态下正确设置为 json 例如 {参考:“2020091600”,相关参考:“2020091601}

现在,我想将这些值直接分配给文本字段

我正在这样做,我不确定在每个字段上使用地图是否是一个好习惯。

<TextField
                    variant="outlined"
                    margin="normal"
                    required
                    autoComplete="off"
                    fullWidth
                    type="text"
                    id="reference"
                    label="Reference"
                    value={viewOutward.map((viewOutward) => viewOutward.reference)}
                    onChange={(e) => setViewOutward(e.target.value)}
                    InputProps={{
                      classes: { input: classes.textfield1 },
                    }}
                    inputProps={{
                      maxLength: 16,
                    }}
                  />

它正在工作,但它可能会影响性能?

有人可以建议仅使用一种状态在文本字段上设置这些值的正确方法。谢谢。

【问题讨论】:

    标签: reactjs ecmascript-6 material-ui


    【解决方案1】:

    假设 API 响应:

    [{reference: "2020091600", relatedReference: "2020091601"}, {reference: "2020091602", relatedReference: "2020091602"}, ...]
    

    在 TextField 中使用状态

    viewOutward.map((item, index) =>
      <TextField
            variant="outlined"
            margin = "normal"
            required
            autoComplete = "off"
            fullWidth
            type = "text"
            id = `${item.reference}` // if reference is unique
            label = "Reference"
            key = { index } // to identity unique for react 
            value = { item.reference } // assign value
            onChange = {(e) =>  //onchange of text assign new value to same object
                     setViewOutward(vo => 
                      vo.map(row => row.reference === item.reference
                      ? { ...row, reference: e.target.value //whatever property you can update 
                      } : row)
                     )
                   }
            InputProps = {{
            classes: { input: classes.textfield1 },
          }}
            inputProps = {{
            maxLength: 16,
          }}
      />
    )
    

    Adding Reference for how to update state of an array of object

    【讨论】:

      猜你喜欢
      • 2020-05-09
      • 2019-07-23
      • 1970-01-01
      • 2019-07-22
      • 2019-12-31
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多