ReactJS - setState Axios POST响应

时间:2018-03-27 14:58:34

标签: javascript reactjs state axios

我试图为我的Axios POST响应设置状态,但是我映射数据的数组仍然是空的。数据提取工作正常,但我只需要使用'主题'移动所有数据。关键字到我的Todos数组并打印出来。

到目前为止,这是我的代码;

App.js

import React, { Component } from 'react';
import axios from 'axios';
import Todos from "./Components/Todos"

class App extends Component {
  constructor(){
    super();
    this.state = {
      todos:[]
    }
  }

  // AXIOS request
  getTodos(){
    var postData = {
      "startDate": "startDate",
      "endDate": "endDate",
      "studentGroup": ["ID"]
    };
    let axiosConfig = {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': "Basic " + btoa("username" + ":" + "password")
      }
    };
    axios.post('url', postData, axiosConfig)
    .then((data) => {
      console.log(data);
      this.setState({todos: data.reservations ? data.reservations : []}, function(){
        console.log(this.state);
      })
    })
    .catch((err) => {
      console.log("Error: ", err);
    })
  }

  componentWillMount(){
    this.getTodos();
  }
  componentDidMount(){
    this.getTodos();
  }

  render() {
    return (
      <div className="App">
        <Todos todos={this.state.todos}/>
      </div>
    );
  }
}
export default App;

Todos.js

import React, { Component } from 'react';
import TodoItem from './TodoItem';

class Todos extends Component {
  render() {
    let todoItems;
    if(this.props.todos){
      todoItems = this.props.todos.map(todo => {
        return (
          <TodoItem key={todo.subject} todo={todo} />
        );
      });
    }
    return (
      <div className="Todos">
        <h3>Results:</h3>
          {todoItems}
      </div>
    );
  }
}
export default Todos;

TodoItem.js

import React, { Component } from 'react';

class TodoItem extends Component {
  render() {
    return (
      <li className="Todo">
        <strong>{this.props.todo.subject}</strong>
      </li>
    );
  }
}
export default TodoItem;

setState之前来自控制台的片段:

enter image description here

我应该使用其他功能而不是箭头功能吗?

3 个答案:

答案 0 :(得分:1)

如果你没有收到this.setState is undefined错误,那就有点奇怪了。你能修复/复制下面的代码并验证是否有帮助:

import React, { Component } from 'react';
import axios from 'axios';
import Todos from "./Components/Todos"

class App extends Component {
  constructor(props){
    super(props);    // pass props to "father" constructor
    this.state = {
      todos:[]
    }
    this.getTodos = this.getTodos.bind(this);
  }

// AXIOS request
getTodos(){
  var postData = {
    "startDate": "startDate",
    "endDate": "endDate",
    "studentGroup": ["ID"]
  };
  let axiosConfig = {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': "Basic " + btoa("username" + ":" + "password")
    }
  };
  axios.post('url', postData, axiosConfig)
  .then((response) => {
    if(response.data.reservations) {
      this.setState({todos: response.data.reservations})
    }
  })
  .catch((err) => {
    console.log("Error: ", err);
  })
}

  componentDidMount(){
    this.getTodos();
  }

  render() {
    console.log(this.state.todos);
    return (
      <div className="App">
        <Todos todos={this.state.todos}/>
      </div>
    );
  }
}
export default App;

现在观察请求完成后是否调用console.log(this.state.todos);。如果是这样,请确认它是一个空数组。

答案 1 :(得分:0)

在函数中创建自引用

getTodos(){
    var self = this; // create a this reference
    var postData = { .. };
    let axiosConfig = {... };
    axios.post(..)
        .then((data) => {
             self.setState('your updated state')
           }) 
        .catch((err) => {});

}

答案 2 :(得分:0)

我很难定义“ this”。我这样解决了(调用函数应该是箭头函数):

 handleGenerateCharge =(event) => {
        const header = new Headers();
        header.append('Access-Control-Allow-Origin', '*');  

        var charge = {
            name: "ABC",
            createDate: Moment(Date.now()).format()
        }

        axios.post("http://url", charge, header)
            .then((res) => {
                if (res.status === 200) {
                    this.update();
                }
            }).catch((error) => {
                this.setState({ errorMessage: error });
            })
        event.preventDefault();
    }