【问题标题】:React Hooks: Value of Input component (Semantic-ui-react) doesn't change after re-renderReact Hooks:输入组件(Semantic-ui-react)的值在重新渲染后不会改变
【发布时间】:2020-07-19 19:01:39
【问题描述】:

我遇到了输入组件的问题。最初,我从 API 获取数据并使用 useState() 挂钩将其分配给变量 (htmlTableData)。接下来将 input 组件的 value 属性设置为变量(变量 htmlTableDatum.value 为 null )。接下来我在输入字段中输入一些值(例如:123)。后来我再次从 API 获取相同的数据,并再次使用 useState() 钩子将其分配给变量 (htmlTableData)。再次将输入组件的 value 属性设置为变量(变量 htmlTableDatum.value 仍然为 null,因为我没有将 123 保存到数据库。我什至控制台记录了 htmlTableDatum.value。htmlTableDatum.value 仍然为 null)。但是输入组件中的值仍然是 123。我不确定是什么问题。(请注意:我不希望强制渲染。我可以通过设置 setHtmlTableData([]) 来做到这一点。但我希望还有另一个方式)

<Table basic='very' celled collapsing>
    <Table.Header>
        <Table.Row>
            <Table.HeaderCell>Name</Table.HeaderCell>
            <Table.HeaderCell>Value</Table.HeaderCell>
            <Table.HeaderCell>Status</Table.HeaderCell>
        </Table.Row>
    </Table.Header>

    <Table.Body>
    {htmlTableData.map((htmlTableDatum) => (
        <Table.Row>
        <Table.Cell>{htmlTableDatum.name}</Table.Cell>
        <Table.Cell><Input value={htmlTableDatum.value} onChange={(e) => setFieldValue(e, htmlTableDatum.name)} /></Table.Cell>
        <Table.Cell textAlign='center'>
            {htmlTableDatum.isValid & htmlTableDatum.isSaved ? <Label circular color='green' empty/> : null}
            {htmlTableDatum.isValid & htmlTableDatum.isSaved == false ? <Label circular color='violet' empty/> : null}
            {htmlTableDatum.isValid == false ? <Label circular color='orange' empty/> : null}
        </Table.Cell>
        </Table.Row>
    ))}
    </Table.Body>
</Table>

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    经过一番努力,我终于找到了问题。

    问题是永远不应该用“null”值初始化 Input 组件的“value”属性。 (即&lt;Input value={null} /&gt;

    如果我们从 API 获取数据并且分配给 Input 组件的值为 null,那么我们可以做这样的事情(即用空字符串初始化):

    const [inputValue, setInputValue] = useState('');
    
    fetch('/getInputValue').then(response => response.json()).then((data) => setInputValue(data.value == null? '': data.value))
    
    render(
       <Input value={inputValue} />
    )
    

    【讨论】:

      猜你喜欢
      • 2020-06-26
      • 2020-02-05
      • 2020-01-13
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      相关资源
      最近更新 更多