【问题标题】:Async/Await no longer works within my dispatched functionAsync/Await 不再在我的调度函数中工作
【发布时间】:2019-12-12 05:45:49
【问题描述】:

我有一个简单的获取请求来获取一些博客文章。

const getBlogPosts = dispatch => {
  return async () => {
    console.log('is this being reached?')
    // const response = await jsonServer.get('/blogposts');
    const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')

    console.log('show me the response: ', await response.json());

    dispatch({ type: 'get_blogposts', payload: response.data });
  };
};

我的减速机:

const blogReducer = (state, action) => {
  // console.log('show me the state inside the reducer: ', action);
  switch (action.type) {
    case 'add_blogpost':
      return [
        ...state,
        {
          id: Math.floor(Math.random() * 999),
          title: action.payload.title,
          content: action.payload.content,
        },
      ];
    case 'get_blogposts':
      console.log('show me action.payload: ', action);
      return action.payload;
    case 'delete_blogpost':
      return state.filter(blogPost => blogPost.id !== action.payload);
    // case 'check_blog':
    //   console.log('wtf??')
    //   return state;
    case 'edit_blogpost':
      return state.map(blogPost => {
        return blogPost.id === action.payload.id ? action.payload : blogPost;
      });
    default:
      return state;
  }
};

我通过以下方式导出 Context 和 Provider:

export const {Context, Provider} = createDataContext(
  blogReducer,
  {addBlogPost, deleteBlogPost, editBlogPost, getBlogPosts},
  [],
);

我的 createDataContext:

import React, {useReducer, useEffect} from 'react';

export default (reducer, actions, initialState) => {
  const Context = React.createContext();
  const Provider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    // actions === { addBlogPost: (dispatch) => {return () => }}

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }
    return (
      <Context.Provider value={{state, ...boundActions}}>
        {children}
      </Context.Provider>
    );
  };
  return {Context, Provider};
};

如果我使用 POSTMAN 向https://jsonplaceholder.typicode.com/todos/1 发出请求,它会返回正常。但是,当我尝试使用 async/await + fetch 做同样的事情时。请求被挂断并且永远不会完成。我也尝试过使用 axios 并遇到了同样的问题。

这是我尝试并正常工作的普通 js。

const fetch = require("node-fetch");

const getBlogPosts = async () => {
    // const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    const response = await fetch('http://5aa599ff.ngrok.io/blogposts');
    const final = await response.json();
    console.log('show me something nice: ', final)

}
getBlogPosts();

【问题讨论】:

    标签: reactjs async-await react-hooks


    【解决方案1】:

    这里 response.data 未定义,因为您的响应对象不包含 data 键。而是使用 response.json() ,这也需要 await 所以做这样的事情:

        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    
        console.log('show me the response: ', await response.json());
    

    这是一个使用端点 https://codesandbox.io/s/react-example-li1pb 的工作示例

    【讨论】:

    • 当我在一个普通的 js 文件中尝试你的代码时,我得到了它的工作。但是,当我回到我的应用程序并尝试它时,我仍然没有看到第二个控制台日志。我只看到“是否已达到”,但没有看到“显示回复”
    • 你能把你的代码添加到沙箱中,这样很容易帮助你吗?你在哪里调用 getBlogPosts 函数?
    • 我已经添加了,但我忘了添加这是一个 react native 项目。我添加了 BlogContext.js 和 createDataContext.js
    • 没关系,我重新启动了系统,一切正常!
    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 2021-08-27
    • 1970-01-01
    • 2021-08-06
    • 2017-12-17
    • 2019-02-17
    相关资源
    最近更新 更多