簡體   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