gpt4 book ai didi

javascript - 更新 api 调用 React 中的设置状态

转载 作者:行者123 更新时间:2023-12-01 02:21:38 24 4
gpt4 key购买 nike

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

问题是因为 this.setState 正在合并对象吗?我很难理解这里发生的事情。如何解决此问题以便将内容传递给 props?

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;

最佳答案

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

关于javascript - 更新 api 调用 React 中的设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49164659/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com