javascript - 在反应中切换按钮时无法查看数据。没有错误
问题描述
单击切换按钮时无法加载人员组件。在控制台中没有发现错误。
下面的代码有什么错误?
加载时无需显示人员组件。单击切换按钮后,我需要显示人员组件以及状态对象人员数组中存在的动态内容。
import React, { Component } from "react";
import Person from "./Person";
class App extends Component {
state = {
showPerson: false,
persons: [
{ id: 1, name: "this is person1", age: 21 },
{ id: 2, name: "this is person2", age: 22 },
{ id: 3, name: "this is person3", age: 23 }
]
};
togglePersons = () => {
const doesShow = this.state.showPerson;
this.setState({ showPerson: !doesShow });
};
render() {
let persons = null;
if (this.state.showPerson) {
persons = (
<div>
{this.state.persons.map((person, index) => {
<Person key={person.id} name={person.name} age={person.age} />;
})}
</div>
);
}
return (
<div>
<h3>This is working</h3>
<button type="button" onClick={this.togglePersons}>
Toggle Persons
</button>
{persons}
</div>
);
}
}
export default App;
Person 组件只是显示存在于 props 对象中的数据
解决方案
工作示例:
class App extends React.Component {
state = {
showPerson: false,
persons: [
{ id: 1, name: "this is person1", age: 21 },
{ id: 2, name: "this is person2", age: 22 },
{ id: 3, name: "this is person3", age: 23 }
]
};
togglePersons = () => {
const doesShow = this.state.showPerson;
this.setState({ showPerson: !doesShow });
};
render() {
const { showPerson, persons } = this.state //Deconstructing your state to improve readability
return (
<div>
<h3>This is working</h3>
<button type="button" onClick={this.togglePersons}>
Toggle Persons
</button>
{showPerson && persons.map(({ id, name, age}) => <p key={id}> {name} : {age} </p>)}
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<div id='root'>
该错误来自您的渲染条件,您忘记在map
.
通过使用内联 if : &&
,您可以根据条件渲染组件。
放入您的JSX{showPerson &&
只会呈现以下代码(如果showPerson
存在)。
您现在只需要用p
您的组件替换标签。
我还建议setState
在使用之前的状态时使用回调版本来避免任何意外行为:
togglePersons = () => {
this.setState(prev => ({ showPerson: !prev.showPerson }))
};
推荐阅读
- gpu - Core ML 中 fp16 计算与 fp32 计算的区别
- python - 如何将 pickle.loads 从 Python 2 转换为 Python 3?
- reactjs - 对如何正确地将道具传递给后代组件感到困惑
- c++ - 由于将位字段类型转换为整数,Valgrind 未初始化字节错误
- pandas - 如何找到一组向量的所有三个向量子集的三重交叉计数?
- flutter - 之前在 Flutter 中是否可以有带有内容的标签栏?
- kubernetes - 如何减少在 Kubernetes 上检测节点故障的时间?
- apache-kafka - 如何生成输入数据并将其存储到本地文件以及我们如何使用 kafka 读取该输入生成文件的数据
- spring - 在 Spring 的 JmsListener 中实例化 IWebContext
- python - 如何限制可以传递给方法参数的允许值(使用类型提示允许静态代码分析)