javascript - 将 API 派生值映射到 React.js 状态的问题

标签 javascript reactjs axios

我是 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,所以我有点难过 - 非常感谢任何帮助!

演示:https://codesandbox.io/s/stoic-neumann-28rhe

最佳答案

问题是 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}`,
  }))
)

then

关于javascript - 将 API 派生值映射到 React.js 状态的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58486510/

相关文章:

javascript - 在另一个 Marionette.ItemView 中调用函数

javascript - 输入类型范围内的进度条

javascript - 在 JSX 参数中 react 渲染组件

reactjs - 将 Redux-Form 与 React-Redux connect 结合使用时出现 TypeScript 错误

reactjs - 使用 redux thunk 测试异步操作

javascript - ReactJS 和 Express with Axios 返回 404 错误消息

javascript - 在 keyup 上获取 iframe 的内容

javascript - NVD3 图表抑制隐藏图表的渲染

javascript - Nodejs 处理上传的文件

javascript - Axios 不发布数据