【问题标题】:Function component doesn't re-render after updating array state in react在反应中更新数组状态后,函数组件不会重新渲染
【发布时间】:2019-10-22 23:06:15
【问题描述】:

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

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

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    状态更新正确,这里缺少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>
        )
    }
    

    另外,不要使用数组indexes as keys.

    【讨论】:

      猜你喜欢
      • 2020-01-13
      • 2022-07-08
      • 2021-01-27
      • 2019-06-17
      • 2017-03-24
      • 1970-01-01
      • 2021-05-19
      • 2022-01-26
      • 2021-11-07
      相关资源
      最近更新 更多