【问题标题】:reactjs importing imported JSON object into array-listreactjs将导入的JSON对象导入数组列表
【发布时间】:2019-10-07 07:06:50
【问题描述】:

我可以显示使用 redux 获得的 JSON 对象。 但是返回时,列表为空。 如何将我发送到列表中的 JSON 对象传输为

有效载荷: 返回 { 类型:USER_INFO, 有效载荷:{ 简介:列表 }, }

export const USER_INFO = 'USER_INFO';

let list = [];

export function userAction(newValue) {

fetch("http://127.0.0.1:8000/api/account/me", {
    headers: {
        Authorization: `Bearer ${localStorage.getItem("id_token")}`,
        "Content-Type": "application/json"
    }
})
    .then((response) => response.json() )
    .then((responseData) =>{
        list = JSON.stringify(responseData);
        console.log(list);
       // console.log(JSON.parse(liste));
        return list;
    });

**//list appears empty when I check here**
**console.log(list);**

return {
    type: USER_INFO,
    payload: {
        profile: list
    },
}
}

【问题讨论】:

  • API调用是异步代码,你的函数在得到响应之前就返回了
  • 请先了解异步编程在 JS 中的工作原理。

标签: arrays json reactjs arraylist


【解决方案1】:

我如何使用 Redux 处理异步请求。

我将为用户信息操作可能具有的每种状态类型提供操作。比如用户信息请求的三种状态:默认、加载、失败。

const userInfoRequest = () => { type: USER_INFO_REQUEST };
const userInfoLoaded = (userInfo) => { type: USER_INFO_LOADED, userInfo };
const userInfoFailed = (error) => { type: USER_INFO_FAILED, error };

您需要将 userInfo 操作转换为 thunk,以便该操作可以在操作创建者内部处理其内部异步状态。

const userInfoRequest = () => (dispatch, getState) => {
  dispatch(userInfoRequest());
  fetch(...)
    .then(response => response.json())
    .then(result => dispatch(userInfoLoaded(result))
    .catch(error => dispatch(userInfoError(error))
}

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 2012-04-03
    • 2021-06-27
    • 2018-11-12
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多