reactjs - 在反应中更新数组状态后,函数组件不会重新渲染
问题描述
我想做一个小反应应用程序来保存短文本条目。该应用程序显示所有已发布的条目,用户可以通过编写和发布来添加新条目。
应用程序有一个string-array (string[])
类型。数组中的每个项目都是一个必须显示在前端条目列表中的条目。
我知道我不能push
进入数组,因为它不会直接改变状态(并且反应没有注意到它必须重新渲染)。所以我用这种方式来获得新的状态:oldState.concat(newEntry)
。但是 React 不会重新渲染它。
这是我的整个反应代码:
function App() {
const [entries, setEntries] = useState([] as string[])
const publish = (entry: string) => {
setEntries(entries.concat(entry))
}
return (
<div>
<Entries entries={entries} />
<EntryInput publish={publish} />
</div>
)
}
function Entries(props: { entries: string[] }) {
return (
<div className="entries">
{props.entries.map((v, i) => { <EntryDisplay msg={v} key={i} /> })}
</div>
)
}
function EntryInput(props: { publish: (msg: string) => void }) {
return (
<div className="entry-input">
<textarea placeholder="Write new entry..." id="input-new-entry" />
<button onClick={(e) => { props.publish((document.getElementById("input-new-entry") as HTMLTextAreaElement).value) }}>Publish</button>
</div>
)
}
function EntryDisplay(props: { msg: string }) {
return (
<div className="entry">{props.msg}</div>
)
}
const reactRoot = document.getElementById("react-root")
ReactDOM.render(<App />, reactRoot)
解决方案
状态已正确更新,此处缺少 return 关键字:
function Entries(props: { entries: string[] }) {
return (
<div className="entries">
{props.entries.map((v, i) => {
// add missing 'return'
return <EntryDisplay msg={v} key={v} />
})}
</div>
)
}
另外,不要使用数组索引作为键。
推荐阅读
- php - 如何在 PHP 中处理多个查询,包括多个 TEMPORARY 表
- linux - 在 docker 容器中创建应用程序(对任务顺序感到困惑)
- php - 如何在 PHP 中从 mongodb/driver/manager 获取集合类对象
- rabbitmq - 当响应来自使用 Spring Integration DSL 的 rabbitMQ 回复队列时,如何实现 HTTP 请求/回复?
- html - HTML不会从scss SASS中获取margin-bottom
- palantir-foundry - 如何分配热键以触发 Slate 中的事件
- sql-server - SQL Server XML 架构验证;无效内容错误;期望将次要事件设置为 0 的元素?
- c# - 无法让包装器 binance.net 正常工作
- snowflake-cloud-data-platform - 雪花配置文件不匹配解释
- r - 无法在“网状”中使用“熊猫”模块