场景一: 更新 state 的一个对象(或数组)属性的某个子属性或值。
使用 Hook Function Component
function App() {
const [arr, updateArr] = useState([]);
const addList = () => {
arr.push('Hello React');
updateArr(arr);
};
return (
<div>
{
arr.map((item, index) => (
<p key={
index}>{
index} {
item}</p>
))
}
<button onClick={
addList}>添加List</button>
</div>
);
}
使用 Class Component
class App extends Component {
constructor(props) {
super(props);
this.state = {
arr: []
}
}
addList = () => {
let arr = this.state.arr;
arr.push('Hello React');
this.setState({
arr: arr
}, ()