gpt4 book ai didi

javascript - ReactJS 状态在第二次 onChange 时更新

转载 作者:行者123 更新时间:2023-12-03 01:59:07 27 4
gpt4 key购买 nike

我是 React 的初学者;我知道 setState 是异步的,但我不明白为什么在示例笔中下方框下方的刷新不会立即完成,而仅在输入第二个字符后才更新。

Codepen:(已更新以链接到正确的笔) https://codepen.io/anon/pen/odZrjm?editors=0010

部分:

// Returns only names matching user's input
filterList = (term) => {
let finalList = []
for (let x = 0; x < this.state.names.length; x++) {
if (this.state.names[x].toLowerCase().includes(term)) {
finalList.push(this.state.names[x])
}
}
finalList.sort()
return finalList
}

// Returns the name list as string
listNames = () => {
let filteredNames = [], filter = this.state.filter.toLowerCase(), names = ""
if (filter === "") return "Enter filter chars"
// Generate filtered array with only names matching filter
filteredNames = this.filterList(filter)
// Build and return comma-separated list of filtered names
names = filteredNames.join(', ')
if (names.length === 0) return 'None found'
return names
}

handleChange = (event) => {
let result, alert = 'alert-primary'
result = this.listNames()
this.setState({
filter: event.target.value,
namesList: result
})
}

如果我将 handleChange 中的“result = this.listNames()”行替换为“result = 'test'”,那么它会立即更新。你能解释一下为什么当我调用函数时它没有出现吗?

最佳答案

发生这种情况是因为您在设置 this.state.filter 之前调用了 listNames 方法,从而达到:

if (filter === "") return "Enter filter chars"

这是一支工作笔:https://codepen.io/anon/pen/gzmVaR?editors=0010

关于javascript - ReactJS 状态在第二次 onChange 时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50119165/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com