reactjs - 使用 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);
解决方案
嘿,react-redux 加载两次是完全自然的行为。
即使我可以解释你,但这不是问题
我确定这种行为没有问题顺便问一下错误名称是什么?
推荐阅读
- php - 如何在 Eloquent ORM 中创建 isAuthorized() 方法?
- r - 在 Mac 上从 R 连接到 Azure SQL Server 数据仓库 - 查看随机名称而不是表
- git - 使用 python 库“pre-commit”,如何添加一个运行单个 python 文件的 git pre-commit 钩子?
- c# - 在 C# 中动态添加控件时,控件出现在 flowLayoutPanel1 之外
- git - Git 合并冲突无法检测到逻辑合并冲突/错误,对吧?
- javascript - 将 img 添加到反应状态以在自定义下拉列表中显示
- c - 如何缩小指针(与 GSL 链接)?
- android - 是否可以通过 L2CAP 连接 iOS (11.4) 和 Android (10+)
- python - 正确设置 POST 方法后,为什么我不断收到 405 错误(不允许使用请求的 URL 的方法。)?
- python - 数据框 - 基于 2 个标准的计算列来查找日/夜