首页 > 解决方案 > 在反应中切换按钮时无法查看数据。没有错误

问题描述

单击切换按钮时无法加载人员组件。在控制台中没有发现错误。

下面的代码有什么错误?

加载时无需显示人员组件。单击切换按钮后,我需要显示人员组件以及状态对象人员数组中存在的动态内容。

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 对象中的数据

标签: javascriptreactjs

解决方案


工作示例:

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 }))
};

推荐阅读