我将搜索输入道具(searchTerm)传递给React组件(图形)。
在dev工具中,Graph组件正在接收正确的prop并且状态正在更新,但我的fetch api函数不会根据更新的prop重新呈现新数据。如果我手动强制数据到API网址,提取工作,所以我知道它必须是我传递searchTerm的方式。我已经尝试过每一次迭代,但仍然无法让它发挥作用。有什么想法吗?
class Graph extends Component {
constructor(props){
super(props);
this.state = {
loaded: false,
now: Math.floor(Date.now()/1000),
data1: [],
searchTerm: DEFAULT_QUERY
}
this.getData = this.getData.bind(this)
}
componentDidMount() {
const {now, searchTerm} = this.state;
this.getData(now, searchTerm);
}
componentWillReceiveProps(nextProps) {
this.setState({searchTerm: nextProps.searchTerm });
}
componentDidUpdate(prevProps) {
const {now, searchTerm} = this.state;
if(this.props.searchTerm !== prevProps.searchTerm) {
this.getData(now, searchTerm);
}
}
getData = (now=this.state.now, searchTerm=this.state.searchTerm) => {
let ticker = searchTerm.toUpperCase();
console.log(searchTerm);
fetch(`https://poloniex.com/public?
command=returnChartData¤cyPair=USDT_${ticker}&end=${now}&period=14400&start=1410158341`)
.then(res => res.json())
.then(results => {
this.setState({
data1:results.map(item => {
let newDate = (item.date)*1000; //*1000
return [newDate,item.close]
})
})
console.log(JSON.stringify(this.state.data1));
})
.then(()=> {
const {data1} = this.state;
this.setState({
min: data1[0][0],
max: data1[data1.length-1][0],
loaded: true})
})
})
}
render() {
const {data1, min, max} = this.state;
return (
<div className="graph">
<HighchartsStockChart>
<Chart zoomType="x" />
<Title>Highstocks Example</Title>
<Loading isLoading={!this.state.loaded}>Fetching data...</Loading>
<Legend>
<Legend.Title></Legend.Title>
</Legend>
<RangeSelector>
<RangeSelector.Button count={1} type="day">1d</RangeSelector.Button>
<RangeSelector.Button count={7} type="day">7d</RangeSelector.Button>
<RangeSelector.Button count={1} type="month">1m</RangeSelector.Button>
<RangeSelector.Button type="all">All</RangeSelector.Button>
<RangeSelector.Input boxBorderColor="#7cb5ec" />
</RangeSelector>
<Tooltip />
<XAxis min={min} max={max}>
<XAxis.Title>Time</XAxis.Title>
</XAxis>
<YAxis id="price">
<YAxis.Title>Price</YAxis.Title>
{this.state.loaded &&<AreaSplineSeries id="price" name="Price" data={data1} />}
</YAxis>
<Navigator>
<Navigator.Series seriesId="profit" />
</Navigator>
</HighchartsStockChart>
</div>
);
}
}