我是 React/Axios 的新手。
我正在尝试通过 Axios 将城市词典 API 中的数据存储到该州的定义空数组中。
然后我尝试通过渲染函数将每个定义的名称渲染到浏览器。
constructor(props) {
super(props);
this.state = {
definitions: [],
errors: null
};
}
componentDidMount() {
this.getUrbDef();
}
getUrbDef() {
axios({
method: 'get',
url: 'https://mashape-community-urban-dictionary.p.rapidapi.com/define',
headers: {'host': 'mashape-community-urban-dictionary.p.rapidapi.com', 'X-RapidAPI-Key': 'keydata'},
params: {'term': 'world'}
})
.then(function (response) {
console.log(response);
})
.then(response =>
response.data.list.map(definition => ({
name: `${definition.definition}`,
id: `${definition.defid}`,
}))
)
.then(definitions => {
console.log(definitions);
this.setState({
definitions,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
// Renders to the browser
render() {
// Grabbing objects to use from state
let definitions = this.state.definitions;
如前所述,这是我第一次以这种方式使用 React.js,所以我有点难过 - 非常感谢任何帮助!
最佳答案
问题是 then
处理程序没有返回任何东西:
.then(function (response) {
console.log(response);
})
解释:
调用 then
会返回一个 Promise,该 Promise 会根据处理函数内部发生的情况得到解决/拒绝。
在你的例子中,处理程序没有返回任何东西 (console.log(response)
),所以 then
返回的 promise 得到了一个未定义的值,结果:
.then(response =>
response.data.list.map(definition => ({
name: `${definition.definition}`,
id: `${definition.defid}`,
}))
)
接收未定义的。
解决此问题的方法是:
1) 在then
处理程序中返回response
:
.then(function (response) {
console.log(response);
return response;
})
2) 从链中删除第一个then
:
axios({
method: 'get',
url: 'https://mashape-community-urban-dictionary.p.rapidapi.com/define',
headers: {'host': 'mashape-community-urban-dictionary.p.rapidapi.com', 'X-RapidAPI-Key': 'keydata'},
params: {'term': 'world'}
})
.then(response =>
response.data.list.map(definition => ({
name: `${definition.definition}`,
id: `${definition.defid}`,
}))
)
关于javascript - 将 API 派生值映射到 React.js 状态的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486510/