【问题标题】:Axios & Redux returns undefined, than resolvesAxios 和 Redux 返回 undefined,然后解析
【发布时间】:2021-07-12 08:39:18
【问题描述】:

我正在使用 react 和 redux 创建一个系统,我需要从 api 获取一些数据,我创建了 action/function 和 reducer,但是当我尝试访问组件上的结果并控制台记录它们时,它显示未定义三倍于解决,当我尝试映射结果时,我当然不能因为未定义的事情。[在此处输入图像描述][1]

这是我的动作函数代码。

import axios from "axios";
import Cookies from "js-cookie";

export const signIn = () => {
    return {
        type: 'LOGGED'
    };
};

export const getCompaniesAction =  (data)  => {
    return{
        type: "GET_COMPANIES",
        payload: data
    };
};

export function fetchCompanies(){
    return(dispatch) => {
        return axios.get(`http://ticketing.mydev.loc/api/companies`, {headers:{
         Authorization: `Bearer ${Cookies.get('access_token')}`
        }}).then(res => res.data.data).then(data => dispatch(getCompaniesAction(data))).catch(err => console.log(err))
    }
}

这里是 mu reducer 函数

const companiesReducer = (state = [], action) => {
    switch (action.type) {
        case 'GET_COMPANIES':
            return{
                ...state,
                companies: action.payload
            }
        default:
            return{
                ...state
            }
    }
}
export default companiesReducer;

这里是商店

const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
const store = createStore(
    allReducers,  compose(applyMiddleware(thunk), composeEnhancer)
)

将状态映射到道具

const mapStateToProps = (state) => ({
    companies: state.companiesReducer.companies
})
export default connect(mapStateToProps, actionCreators)(Company);

组件确实挂载了

  componentDidMount() {
        this.props.fetchCompanies()
    }

在这里我尝试访问数据

   render(){
       if(this.props.companies !== 'undefined'){
           console.log(this.props.companies)
       }

所以我的 redux devtool 完美地显示了状态变化,但是组件中的这个 console.log 显示 undefined 是显示数据的三倍。 感谢您的宝贵时间

【问题讨论】:

    标签: reactjs redux react-redux axios redux-thunk


    【解决方案1】:

    未定义是companies 未初始化状态的结果。 "undefined" 也是一个字符串,而不是值 undefined。试试这样检查

    render(){
           if(this.props.companies !== undefined){
               console.log(this.props.companies)
           }
    

    【讨论】:

      【解决方案2】:

      那是因为你的 fetchCompanies 是异步的,所以当你的数据被获取时,有些东西会触发你的组件中的重新渲染。

      您可以在加载数据并呈现加载消息时添加新状态并对其进行管理,或者您可以使用componentShouldUpdate 检查您的道具并决定您的组件是否应该更新

      【讨论】:

        猜你喜欢
        • 2018-02-21
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 2016-11-20
        • 1970-01-01
        • 2019-02-27
        • 1970-01-01
        相关资源
        最近更新 更多