péter Leéh的评论解决了这个问题:映射this.state.projects而不仅仅是项目。Thx!
我的代码的addProject函数正在正确更新状态,但之后不会将新项目添加到DOM中。为什么?
到目前为止我尝试了什么:
- forceUpdate((
- 对阵列进行了深入复制
- 将地图的关键字更改为项目标题
import React from 'react'
const productBacklog = [
{ id: 1, text: 'FrontEnd'},
{ id: 2, text: 'Finished page - for Cluster'}
];
const parkingLot = [
{ id: 1, text: 'Home page: Google Log In/Github API ---Update: Have Google Cloud account for this'},
{ id: 2, text: 'Screenshots of steps needed to setup test class w/annotation & imports' },
];
const projects = [
{ id: 1, title: 'Parking Lot', children: parkingLot },
{ id: 2, title: 'Product Backlog', children: productBacklog }
];
export default class App extends React.Component {
constructor() {
super();
this.state = {
projects: projects,
}
}
addProject = () => {
const newProject = {
id: Math.round(Math.random() * 1000000),
title: 'newProject',
children: [],
}
const projects = [...this.state.projects];
projects.push(newProject);
this.setState({projects: [...projects]}, () => {
console.log(this.state.projects) // SHOWS THAT STATE IS UPDATED CORRECTLY
})
}
render () {
return (
<div className='App'>
<input type='button' value='Add project' onClick={this.addProject}/>
<div className='projects'>
{projects.map((project, projectId) =>
<div className='Project' key={projectId}>
Project-Title: { project.title}
</div>
)}
</div>
</div>
)
}
}
正如我在评论中所说,您需要在this.state.projects
上进行映射。你应该仔细命名事物。。这只是因为您有一个名为projects
的全局变量(它与组件的状态同步,在我看来这是个坏主意(,否则这将是一个明显的错误。此外,我认为功能组件有点好:
import React, { useState } from 'react';
const productBacklog = [
{ id: 1, text: 'FrontEnd'},
{ id: 2, text: 'Finished page - for Cluster'}
];
const parkingLot = [
{ id: 1, text: 'Home page: Google Log In/Github API ---Update: Have Google Cloud account for this'},
{ id: 2, text: 'Screenshots of steps needed to setup test class w/annotation & imports' },
];
const projects = [
{ id: 1, title: 'Parking Lot', children: parkingLot },
{ id: 2, title: 'Product Backlog', children: productBacklog }
];
export default function App() {
const [state, setState] = useState({projects: projects})
const addProject = () => {
const newProject = {
id: Math.round(Math.random() * 1000000),
title: 'newProject',
children: [],
}
setState({projects: [...state.projects, newProject]})
}
return (
<div className='App'>
<input type='button' value='Add project' onClick={addProject}/>
<div className='projects'>
{state.projects.map((project, projectId) =>
<div className='Project' key={projectId}>
Project-Title: { project.title}
</div>
)}
</div>
</div>
)
}