React 和 JS 对我来说总体来说是新的,所以我在这方面仍然有点糟糕。在整个情况下,我最不了解的是 React Hooks 以及它们有时不更新的问题。我知道为什么以及如何避免多次调用 setter 之类的事情,但是这个特殊问题对我来说很难理解,甚至很难正确地谷歌搜索。我要么在这里找到基于类的 this.state 内容,要么找到未解答的问题。
如何在需要时更新 Hook 。例如,这是来自 Material-UI 的 Autocomplete
组件。当我在其中选择一个选项时,我想将其值放入 getTables
中的 newFKSchema const 中以使用它。此方法中只有前三行对于这个问题很重要。但console.log显示newFKSchema为空。如果我选择另一个选项,newFKSchema 将包含之前的选项。所以就像是一回合的延迟。我不明白为什么会发生这种情况以及如何让它按照我想要的方式工作。抱歉,代码很乱,我已经做了一些尝试来使其工作。
如果对您来说不难,请在提供解决方案后稍微解释一下。
const allSchemas = [
'',
'ADDITIONAL',
'BOOKKEEPING',
'CB',
'DEPOSIT',
'DOGORG',
'GENERALUSE',
'NSI',
'PAYMENTS',
'PLASTIC',
'SAFECELL',
'SWIFT',
'TARIFF',
];
const [newFKSchema, setNewFKSchema] = React.useState(allSchemas[0]);
const getTables = (schema) => {
var newSchema = schema;
setNewFKSchema(newSchema);
console.log(newFKSchema);
if (newFKSchema !== '') {
superagent
.get('/api/tech')
.query({schema: schema})
.then((response) =>{
if (response.status === 200) {
const newTables = [];
response.body.forEach(e => {newTables.push(e)});
setAllTables(newTables);
}
})
.catch(error => {
if (error.response.statusCode === 400) {
alert("No tables were found!");
}
});
}
}
<FormControl fullWidth>
<Autocomplete
id="autocomplete-schema"
options={allSchemas.slice(1)}
value={newFKSchema}
onChange={(event, value) => {setNewFKSchemaError(false); getTables(value)}} //setNewFKSchema(value);
renderInput={(params) => <TextField {...params} label="Schema name" variant="outlined" fullWidth />} />
<FormHelperText className={classes.formHelper}>
{newFKSchemaError ? "Needs input!" : ''}
</FormHelperText>
</FormControl>
最佳答案
好的,让我们来看看这里发生了什么:
您在 onChange
触发器中调用 getTables(value)
,并使用参数 event
和 value
。
value
设置为 newFKSchema
,您将其定义为 allSchemas[0]
,即 ''
然后你这样做:
const getTables = (schema) => {
var newSchema = schema;
setNewFKSchema(newSchema);
console.log(newFKSchema);
我们知道架构是''
。所以 newSchema 也将是 ''
并且 setNewFKSchema 也会将 schema 设置为 ''
,显然控制台日志也会记录 ''
那么,您到底期望发生什么?
关于javascript - React Hook 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61986042/