单击切换按钮时无法加载人员组件。在控制台中未发现错误。
以下代码有什么错误?
加载时无需显示人员组件。一旦单击切换按钮,我需要显示具有状态对象人员数组中存在的动态内容的人员组件。
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:
&&
,可以根据条件渲染组件。如果
{showPerson &&
存在,则将showPerson
放入JSX只会渲染以下代码。现在,您只需要用组件替换
p
标记。我还建议在使用以前的状态时使用
setState
的回调版本,以避免任何意外的行为:togglePersons = () => {
this.setState(prev => ({ showPerson: !prev.showPerson }))
};
关于javascript - 在 react 中切换按钮时无法查看数据。没错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54495984/