在api调用中更新set state反应

时间:2018-03-08 03:01:01

标签: javascript reactjs state

我在API调用中设置this.setState时遇到问题。如果我在console.log中调用axios中的stocks数组,则数据在数组中可用。如果它在外面不可用。

问题是因为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;

1 个答案:

答案 0 :(得分:2)

你的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访问股票