Json 在通过 axios 库方法设置其状态后,ReactJS class 中未呈现数据?

Json Data not rendering in ReactJS class after setting its state through axios library method?

我正在尝试通过 axios 库函数 axios.get() method.It 读取 JSON 数据 method.It 工作正常并在控制台中记录正确的用户名并正确设置用户状态 variable.But 当我尝试在 render method() 中渲染同一个对象时它停止工作。 Link 到 CODE on codepen

class TableData extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users:[],
      count: 0
    };
  }
  componentDidMount() {
    axios
      .get(`https://fcctop100.herokuapp.com/api/fccusers/top/recent`)
      .then(response => {
        this.setState({ users: response.data });
        console.log(this.state.users[2].username);
      });
  }
  render() {
    return (
      <div>Hello {this.state.users[2].username}</div>
    );
  }
}
ReactDOM.render(<TableData />, document.getElementById("container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.12.0/axios.min.js"></script>
<div class="container" id="container">

</div>

URL for JSON 数据 return 类型

对象

Object {
  alltime: 388,
  img: "https://avatars3.githubusercontent.com/u/36005?v=3",
  lastUpdate: "2017-10-17T08:05:51.276Z",
  recent: 124,
  username: "korzo"
}

请帮助我。

有一段时间this.state.users是一个空数组。所以当你的渲染函数访问 this.state.users[2].username 时,this.state.users[2] 可以是未定义的,抛出异常。你只需要改变你的渲染函数来处理数组为空的情况。

另请注意,this.setState 可以是异步的,因此调用 setState 后的日志语句可能看不到新状态。如果想等到setState完成,可以传入一个回调函数给this.setState

class TableData extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      users:[],
      count: 0
    };
  }
  componentDidMount() {
    axios
      .get(`https://fcctop100.herokuapp.com/api/fccusers/top/recent`)
      .then(response => {
        this.setState({ users: response.data }, function () {
          console.log(this.state.users[2].username);
        });
      });
  }
  render() {
    return (
      <div>Hello {this.state.users[2] && this.state.users[2].username}</div>
    );
  }
}
ReactDOM.render(<TableData />, document.getElementById("container"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.12.0/axios.min.js"></script>
<div class="container" id="container">

</div>

render 方法正在尝试渲染 this.state.users[2].username,它是 undefined 在组件装载上。

您的渲染方法应该是这样的,以便仅在 this.state.users 数组有 2 个或更多元素时渲染。

render() {
  return this.state.users.length > 1 ? (
    <div>Hello {this.state.users[2].username}</div>
  ) : null;
}

另外,我不认为 console.log(this.state.users[2].username); 应该返回正确的数据,因为 setState 是异步的。