【发布时间】:2020-02-05 19:32:58
【问题描述】:
我无法弄清楚为什么我在 React 中的函数组件中的原型会因此而失败:
`index.js:1 Warning: Failed prop type: The prop `profiles` is marked as required in `Home`, but its value is `undefined`.`
应用程序运行良好,配置文件已定义,我正在使用带有钩子的 React-redux,这可能会导致问题,因为我实际上不知道如何使 PropTypes 工作
出现这种情况的我的家:
import React, { useEffect, useState } from "react";
import { Row, Col, Jumbotron, Container, Image } from "react-bootstrap";
import { ProfileMiddleware } from "../Store/Middleware";
import { PropTypes } from "prop-types";
import { useDispatch, useSelector } from "react-redux";
import { USERNAME } from "../Services/constAPI";
import Experiences from "../Components/Experiences/Experiences";
import { Spinner } from "../Components/Spinner/Spinner.js";
const Home = () => {
const dispatch = useDispatch();
const { profiles, displaySpinner } = useSelector(state => ({
profiles: state.ProfileReducer.profiles,
displaySpinner: state.ProfileReducer.displaySpinner
}));
useEffect(() => {
dispatch(ProfileMiddleware.getOneProfile(USERNAME));
}, [dispatch]);
return !profiles.object ? (
<>
<Jumbotron>
<Container>
<Row>
<Col md={6}>
<Image src={profiles.imageUrl} alt="profile" roundedCircle />
</Col>
<Col md={6}>
<h1>{profiles.firstname + " " + profiles.surname}</h1>
<h4>{profiles.title}</h4>
<h5>{profiles.area}</h5>
<p>{profiles.email}</p>
<p>{profiles.bio}</p>
</Col>
</Row>
<Spinner displaySpinner={displaySpinner} />
</Container>
</Jumbotron>
<Experiences />
</>
) : (
<h3 className="red-text mt-5">The profile is not available</h3>
);
};
Home.propTypes = {
profiles: PropTypes.object.isRequired
};
export default Home;
我使用 Redux 时的 reducer
import { ProfileActions } from "../Actions";
function ProfileReducer(
state = {
profiles: {},
displaySpinner: false
},
action
) {
console.log("data in action", action.data);
console.log("Action type", action.type);
switch (action.type) {
case ProfileActions.GET_ONE_PROFILE:
return {
...state,
displaySpinner: true
};
case ProfileActions.GET_ONE_PROFILE_SUCCESS:
return {
...state,
profiles: action.data,
displaySpinner: false
};
default:
return state;
}
}
export default ProfileReducer;
如有必要,我可以显示其他内容,但 APP 可以工作,但 PropTypes 说配置文件未定义,我无法理解。
【问题讨论】:
-
您似乎没有将任何道具传递给
Home。你为什么要这样做,然后又试图要求profiles道具? -
我必须使用 PropTypes 检查配置文件是否为 obj 我正在尝试找到解决方案以使其正常工作。如果您知道解决方案,请分享答案
标签: reactjs react-redux react-hooks