更新在API调用设定状态发生反应(updating set state in api call re

2019-10-28 12:58发布

我在从我的API调用内设置this.setState问题。 如果我CONSOLE.LOG股票阵列内的Axios公司拨打的数据是阵列中可用。 它不是,如果它的外部可用。

是问题,因为this.setState被合并的对象? 我有一个很难概念化这里发生了什么。 如何解决这个问题,所以我可以通过内容的道具?

import React, { Component } from 'react';
import axios from 'axios';

import SearchBar from './components/search_bar';
import StockList from './components/StockList';
import './App.css';

class App extends Component {
constructor() {
super();

this.state = {
  stocks: [],
  term: null,
  value: ''
};

this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
}

handleChange(e) {
this.setState({
  value: e.target.value
});
}

handleClick(e) {
if(e) e.preventDefault();
this.setState({
  value: '',
  term: this.state.value
});

let term = this.state.value;
const key = 'F41ON15LGCFM4PR7';
const url = `https://www.alphavantage.co/query?function=BATCH_STOCK_QUOTES&symbols=${term}&apikey=${key}`;

axios.get(axios.get(url)
.then(res => {
  let stocks = Array.from(res.data['Stock Quotes']).map((stock) => [{symbol: stock['1. symbol'], price: stock['2. price'], volume: stock['3. volume'], timestamp: stock['4. timestamp']}]);

  this.setState((state, props) => {
    return [...this.state.stocks]
  })
})
.catch(error => console.log(error))
)
}

render () {
let stocks = this.state.stocks;
const value = this.state.value;
return (
  <div className="App">
    <h1>Stock Search</h1>
    <SearchBar value={ value }
               onChange={ this.handleChange }
               onClick={ this.handleClick }/>
    <StockList stockItems={ stocks }/>
  </div>
);
}
}

export default App;

Answer 1:

你的setState有问题,它搞乱你的结构状态。

this.setState((state, props) => {
    return [...this.state.stocks]
});

应该是:

this.setState({
    // set stocks to that array you parsed from the axios response
    stocks
});

要么

this.setState((state, props) => {
    return {
        ...state,
        // set stocks to that array you parsed from the axios response
        stocks
    };
});

我建议,因为您是通过访问个股this.state.stocks在渲染



文章来源: updating set state in api call react