Javascript React-redux:使用axios请求启动状态,避免未定义
我正在使用React redux。我有我的reducer'sellerHandler.jsx',我想用axios调用启动他的状态。我的问题是:我的状态是未定义的,我猜是因为axios是一个异步函数Javascript React-redux:使用axios请求启动状态,避免未定义,javascript,reactjs,react-redux,axios,jsx,Javascript,Reactjs,React Redux,Axios,Jsx,我正在使用React redux。我有我的reducer'sellerHandler.jsx',我想用axios调用启动他的状态。我的问题是:我的状态是未定义的,我猜是因为axios是一个异步函数 import axios from "axios"; function getUser() { axios .get("/xhr/seller/get") .then(respon
import axios from "axios";
function getUser() {
axios
.get("/xhr/seller/get")
.then(response => response.data)
.then(data => {
console.log(data.seller);
return data.seller;
})
}
const initialState = { seller: getUser() }
console.log(initialState.seller);
function sellerHandler(state = initialState, action) {
let nextState;
switch(action.type) {
case 'REPLACE_SELLER':
nextState = {
...state,
seller: action.seller
}
return nextState;
case 'RESET_SELLER':
nextState = {
...state,
seller: null
}
return nextState;
default:
return state;
}
}
export default sellerHandler;
axios调用中的console.log输出:
{id: 2426, firstname: "Martin", lastname: "Bosco"}
当一个外部输出“未定义”时
当我的应用程序第一次加载时,我希望我的sellerHandler(reducer)使用一个种子值进行初始化,这是axios查询返回的结果 我怎样才能使这个代码工作 解决方案:
使用HOC在我的应用程序中的任何操作之前启动我的reducer状态我想你希望在reducer中使用你的值。但是你还没有从action中发送任何内容,它将如何响应?当我的应用程序第一次加载时,我希望我的sellerReducer具有默认值,即我的axios调用返回的值。你是否使用了红色ux之前?因为您只是从函数返回值的方式不会触发任何操作创建者。好的,我知道您在这里做什么。但问题是axios是异步请求。它会请求服务器获取数据,然后它会做出响应。因此您可能没有准确的时间获得这些值。您应该尝试HOC。是的,我知道这是一种方式关于异步调用,我不知道什么是HOC,我会检查这个,thx mate