繁体   English   中英

用 object 填充数组(使用 setState)

[英]Fill an array with an object (using setState)

我正在尝试使用从 axios 请求返回的对象数组填充数组。 但是,该数组返回为空。

export default class Todo extends Component {
constructor(props){
    super(props)
    this.state = { description: '', list: [] }

    this.handleChange = this.handleChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)

    this.refresh();

}

    refresh() {
        axios.get(`${URL}?sort=-createdAt`)
            .then(resp => this.setState({...this.state, description: 'Qualquer valor', list: resp.data}))
            //.then(resp => console.log(resp.data))

            console.log(this.state.list)
    }

我在构造函数中初始化数组(名为“List”),然后,在刷新 function 之后,页面加载后立即调用,我收到 axios 请求的响应,并尝试用数据返回值,但它不起作用。

Obs:我已经保证请求返回良好,并且“resp.data”包含我想要推送到名为“list”的数组的数据(响应返回一个对象数组)

If you call function from constructor and in that function try to update state than react will not throw warning and will not update state.

So instead of calling function in constructor, try to call function in componentDidMount like below and try to access updated state value in callback function:-

constructor(props){
    super(props)
    this.state = { description: '', list: [] }

    this.handleChange = this.handleChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
}

componentDidMount() {
  this.refresh();
}

  refresh() {
    axios.get(`${URL}?sort=-createdAt`).then(resp =>
      this.setState(
        {
          description: 'Qualquer valor',
          list: resp.data
        },
        () => {
          console.log(this.state.list);    // here this will print updated list
        }
      )
    );
  }

axios 请求调用必须在 componentDidMount 生命周期钩子中调用 go,而不是构造函数。

更多详细信息请参阅文档:https://reactjs.org/docs/react-component.html#componentdidmount

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM