我在获取请求后使用一系列 then 语句来转换数据。代码在 React 应用程序中,但我认为这只是一个 Javascript 问题。
这是我当前的代码:
componentDidMount(){
fetch(this.state.dataRouteDirections)
.then(data => data=data.json())
.then(data => console.log(data))
.then(data => data.unshift(this.state.emptyDirections))
.then(data => this.setState({directions:data}))
.then(()=>{
var makes = this.state.directions.map(directions=>directions.acf.make); //get all make categories
function removeDuplicates(arr){
let unique_array = arr.filter(function(elem, index, self) {
return index===self.indexOf(elem);
});
return unique_array
}
makes = removeDuplicates(makes);
this.setState({makes:makes});
})
}
给我带来麻烦的那一行是“.then(data => data.unshift(this.state.emptyDirections))”。它告诉我变量数据在此语句中未定义。事实上,如果我将这一行替换为与上面相同的行,控制台记录数据两次,第一个控制台日志正确记录,第二个未定义。
我对 fetch/then/JS 有什么不理解的地方?我来自 PHP 背景,异步内容仍然是一个挑战。
下面回答了问题,这是我更新的代码:
componentDidMount(){
fetch(this.state.dataRouteDirections)
.then(data => data=data.json())
.then(data => {data.unshift(this.state.emptyDirections); return data;})
.then(data => this.setState({directions:data}))
.then(()=>{
var makes = this.state.directions.map(directions=>directions.acf.make); //get all make categories
function removeDuplicates(arr){
let unique_array = arr.filter(function(elem, index, self) {
return index===self.indexOf(elem);
});
return unique_array
}
makes = removeDuplicates(makes);
this.setState({makes:makes});
})
}
最佳答案
你有这个的原因是因为 console.log(data)
返回 undefined
。你应该这样写:
.then(data => {console.log(data); return data})
关于javascript - Fetch/Then 链行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48993949/