[在此处输入图片说明][1]
我试图将我的 React 前端连接到我的 Spring Boot 后端。我遇到了这个错误。如何解决这个问题? *我是一个 react 和 javascript 新手,正在尝试构建一个新的应用程序。我尝试了另一个堆栈溢出的解决方案,但似乎没有任何效果。 * [1]:https://i.stack.imgur.com/vaxWI.png
import React, { Component } from "react";
import ProjectItem from "./Project/ProjectItem";
import CreateProjectButton from "./Project/CreateProjectButton";
import { connect } from "react-redux";
import { getProjects } from "../actions/projectActions";
import PropTypes from "prop-types";
import Projects from './Projects';
class Dashboard extends Component {
constructor(props){
super(props);
}
componentDidMount() {
this.props.getProjects();
}
render() {
const { projects } = this.props.project;
return (
<div className="projects">
<div className="container">
<div className="row">
<div className="col-md-12">
<h1 className="display-4 text-center">Projects</h1>
<br />
<CreateProjectButton />
<br />
<hr />
{projects.map((project) => (<ProjectItem key={project.id} project={project} ></ProjectItem>))}
</div>
</div>
</div>
</div>
);
}
}
Dashboard.propTypes = {
project: PropTypes.object.isRequired,
getProjects: PropTypes.func.isRequired
};
const mapStateToProps = state => ({
project: state.project
});
export default connect(
mapStateToProps,
{ getProjects }
)(Dashboard);
import React,{ useState } from 'react'
import ProjectItem from './Project/ProjectItem';
const Projects = (props) => {
return(
<div>
{props.projects.map((project) => (<ProjectItem key={project.id} project={project} ></ProjectItem>))}
</div>
)
}
export default Projects;
//dispatch redux func
export const getProjects = () => async dispatch => {
const res = await axios.get("/api/projects");
dispatch({
type: GET_PROJECTS,
payload: res.data
});
};
答案 0 :(得分:2)
注意项目 props 是一个数组数据,以便能够遍历它(不是 null、undefined、object)。 你也可以使用可选的链接运算符:'?'
(projects?.data)
在 create-react-app 中启用可选链:
How to enable optional chaining with Create React App and TypeScript
答案 1 :(得分:0)
尝试添加可选的链接运算符:'?'在点符号之前:
projects?.map
代替
projects.map