首页 > 解决方案 > 在反应中更新数组状态后,函数组件不会重新渲染

问题描述

我想做一个小反应应用程序来保存短文本条目。该应用程序显示所有已发布的条目,用户可以通过编写和发布来添加新条目。

应用程序有一个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)

标签: reactjstypescript

解决方案


状态已正确更新,此处缺少 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>
    )
}

另外,不要使用数组索引作为键。


推荐阅读