如何在react中进行fetch?

2024-03-12

下午好,我从服务器获取json,我处理它,但是对渲染的调用发生了2次。Google,在构造函数中创建一个空对象。如果该对象没有属性,则返回 undefined ,但我也有数组,应用程序从中崩溃。我附上代码。如何将数据取出状态?是否可以在渲染中获取并写入?

export default class Forma extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentWillMount() {
    fetch("http://localhost:3001")
      .then(response => response.json())
      .then(result => this.setState({ data: result }))
      .catch(e => console.log(e));
  }

  render() {
    const { data } = this.state;

    return <h1>{console.log(data.goals[0].gs_id)}</h1>; //падает
  }
}

Use componentDidMount代替componentWillMount,它已被弃用。

这是 Christopher 处理异步操作的答案中非常好的补充。

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then(response => response.json())
      .then(result =>
        this.setState({
          data: result
        })
      )
      .catch(e => console.log(e));
  }
  render() {
    const { data } = this.state;

    return <h1> {data[0] ? data[0].title : 'Loading'} </h1>;
  }
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在react中进行fetch? 的相关文章

随机推荐