【发布时间】:2020-09-14 11:07:32
【问题描述】:
我有 3 个元素,我想通过单击任何 div 添加一个新元素,但问题是在将新元素添加到数组后,它们不会从组件中渲染出来。
import React, { useState } from "react";
import "./styles.css";
export default function App() {
let elements = [
{ id: 0, text: "first" },
{ id: 1, text: "second" },
{ id: 2, text: "third" }
];
const [state, setstate] = useState(elements);
function handleClick() {
elements.push({ id: 3, text: "xxx", checkBox: null });
setstate(elements);
console.log(state); //state shows 4 elememnt but they don't render in
}
return (
<div className="App">
{state.map((e) => (
// why this don't render the new elements?
<div onClick={handleClick}>{e.text}</div>
))}
</div>
);
}
in codesandboxhttps://codesandbox.io/s/beautiful-silence-c1t1k?file=/src/App.js:0-641
【问题讨论】:
标签: javascript arrays reactjs react-hooks rendering