首页 > 解决方案 > 使用 redux 反应组件加载两次

问题描述

我正在尝试从 redux 存储中获取状态,但是每当我访问我的 redux 操作时,我的组件都会加载两次通过第一次手动加载路由它返回两个对象,一个为空状态的对象和另一个更新状态的对象但是当我切换时在路由之间它返回新状态,但每次两次或两个相同状态的对象。

这会导致加载组件时出现未定义的错误,特别是在手动加载路由时,当我访问任何状态属性时,

Redux action
export function getRelationshipStatus() {
    let headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('access_token')}`
    }
    return dispatch => {
        axios.get('http://localhost/relation/api/get-relationship-status', { headers })
        .then(  response => dispatch({type:ActionTypes.GET_RELATIONSHIP_STATUS,payload:response.data}))
    }
};

减速器

import React from 'react'
import {GET_RELATIONSHIP_STATUS} from  '../actions/action-types'
const initialState={
    profile:{},
}
export default function (state=initialState,action) {
    switch(action.type){
        case GET_RELATIONSHIP_STATUS:
        console.log(action.payload);
        return {...state,profile:action.payload}
        break;
        default:
        return state
    }
}

实际组件

import React, { Component } from 'react'
import {connect} from 'react-redux'
import {getRelationshipStatus} from '../../store/actions'
 class People extends Component {
     constructor(props){
         super(props)
     }
      componentDidMount(){
        this.props.getRelationshipStatus()
    }
    render() {
        console.log(this.props.profile)

        return (
            <div>


            </div>
        )
    }
}


function mapStateToProps(state) {
    return {
        profile: state.profile,
    }
}
export default connect(
    mapStateToProps,
    { getRelationshipStatus }
)(People);

标签: reactjs

解决方案


嘿,react-redux 加载两次是完全自然的行为。

即使我可以解释你,但这不是问题

我确定这种行为没有问题顺便问一下错误名称是什么?


推荐阅读