【发布时间】:2021-02-22 19:28:04
【问题描述】:
** 我想将 props 存储在 state 中,但我写的是“* TypeError: Cannot read property 'fullName' of null *” 这里是截图 ** 我从容器组件中获取 props https://ibb.co/dJkfrWh 我提供我的容器组件和减速器。当我在州外使用道具时,一切正常,我只需将所有这些道具保存在州内
import React from 'react';
import { MonthBox } from './Month/Month';
export class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
accountSettings: [
{
titleSettings: "Username",
fullName: this.props.profile.fullName,
icon: faUser,
},
{
titleSettings: "Looking for a job",
fullName: this.props.profile.lookingForAJob,
icon: faUser,
},
{
titleSettings: "Looking for a job description",
fullName: this.props.profile.lookingForAJobDescription,
icon: faUser,
},
{
titleSettings: "User ID",
fullName: this.props.profile.userId,
icon: faUser,
},
]
};
}
render() {
if (!this.props.profile) {
return <p>Loading...</p>
}
const d = new Date();
const n = d.getMonth();
return (
<div>
// Removed to JSX shorten the code
</div>
)
}
}
ProfileContainer.js
import React from 'react';
import {connect} from 'react-redux';
import {Profile} from './Profile';
import {profileAC} from "../Redux/profile-reduer";
import * as axios from "axios";
import withRouter from "react-router-dom/es/withRouter";
class ProfileReducer extends React.Component {
componentDidMount() {
let userId = this.props.match.params.userId;
axios.get('https://social-network.samuraijs.com/api/1.0/profile/' + userId).then(response => {
this.props.profileAC(response.data);
})
}
render() {
return <>
<Profile {...this.props} />
</>
}
}
let mapStateToProps = (state) => ({
profile: state.profile.profile,
})
let urlDataRouter = withRouter(ProfileReducer)
export default connect(mapStateToProps, {profileAC})(urlDataRouter);
profile-reducer.js
const ADD_PROFILE = "ADD_PROFILE";
let initialState = {
profile: null,
}
export const profileReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PROFILE:
return {
...state, profile: action.profile
}
default:
return state;
}
}
export const profileAC = (profile) => ({
type: ADD_PROFILE, profile
})
【问题讨论】:
-
您没有提供足够的信息来理解为什么 this.props.profile 具有未定义的 fullName 值。向我们展示容器组件和相关的 redux 代码
-
我不知道你的用例,但它通常被认为是一种反模式,用于将传递的道具存储到本地组件状态(异常通常处理随着时间的推移)。相反,您应该尝试始终直接在渲染中使用传递的道具。这将消除接收到的道具和本地状态之间的任何同步问题。
-
查看我的回答更新
标签: reactjs react-redux state store