Javascript 无法更新状态
我正在使用MERN和Redux 我有一个clickHandler函数,它调用从我的操作导入的findAuthor函数。这将根据用户的id查找用户并将其返回。我已将用户添加到全局状态。然后我想检索用户并将其名称添加到本地状态,但我无法使其正常工作。我一直收到这样的错误类型错误:this.props.subAuthor未定义。我错过了什么?当我尝试打印到控制台时,直到第二次单击,我才看到任何对象。我怎样才能让它立即更新Javascript 无法更新状态,javascript,reactjs,redux,react-redux,mern,Javascript,Reactjs,Redux,React Redux,Mern,我正在使用MERN和Redux 我有一个clickHandler函数,它调用从我的操作导入的findAuthor函数。这将根据用户的id查找用户并将其返回。我已将用户添加到全局状态。然后我想检索用户并将其名称添加到本地状态,但我无法使其正常工作。我一直收到这样的错误类型错误:this.props.subAuthor未定义。我错过了什么?当我尝试打印到控制台时,直到第二次单击,我才看到任何对象。我怎样才能让它立即更新 import React, { Component } from "r
import React, { Component } from "react";
import PropTypes from "prop-types";
import GoogleSearch from "./GoogleSearch";
import { connect } from "react-redux";
import { fetchSubjects } from "../../actions/subject";
import { fetchComments } from "../../actions/comment";
import { updateSubject } from "../../actions/subject";
import { getUser } from "../../actions/authActions";
class Subject extends Component {
// on loading the subjects and comments
// are fetched from the database
componentDidMount() {
this.props.fetchSubjects();
this.props.fetchComments();
}
constructor(props) {
super(props);
this.state = {
// set inital state for subjects
// description, summary and comments all invisible
viewDesription: -1,
viewSummary: -1,
comments: [],
name: "",
};
}
componentWillReceiveProps(nextProps) {
// new subject and comments are added to the top
// of the arrays
if (nextProps.newPost) {
this.props.subjects.unshift(nextProps.newPost);
}
if (nextProps.newPost) {
this.props.comments.unshift(nextProps.newPost);
}
}
clickHandler = (id) => {
// when a subject title is clicked pass in its id
// and make the description and comments visible
const { viewDescription } = this.state;
this.setState({ viewDescription: viewDescription === id ? -1 : id });
// add relevant comments to the state
var i;
var temp = [];
for (i = 0; i < this.props.comments.length; i++) {
if (this.props.comments[i].subject === id) {
temp.unshift(this.props.comments[i]);
}
}
this.setState({
comments: temp,
});
// save the subject id to local storage
// this is done incase a new comment is added
// then the subject associated with it can be retrieved
// and added as a property of that comment
localStorage.setItem("passedSubject", id);
//testing getUser
this.findAuthor(id); // this updates the tempUser in state
this.setState({ name: this.props.subAuthor.name });
};
// hovering on and off subjects toggles the visibility of the summary
hoverHandler = (id) => {
this.setState({ viewSummary: id });
};
hoverOffHandler = () => {
this.setState({ viewSummary: -1 });
};
rateHandler = (id, rate) => {
const subject = this.props.subjects.find((subject) => subject._id === id);
// when no subject was found, the updateSubject won't be called
subject &&
this.props.updateSubject(id, rate, subject.noOfVotes, subject.rating);
alert("Thank you for rating this subject.");
};
// take in the id of the subject
// find it in the props
// get its author id
// call the getUser passing the author id
findAuthor(id) {
console.log("Hitting findAuthor function");
const subject = this.props.subjects.find((subject) => subject._id === id);
const authorId = subject.author;
console.log(authorId);
this.props.getUser(authorId);
}
render() {
const subjectItems = this.props.subjects.map((subject) => {
// if the state equals the id set to visible if not set to invisible
var view = this.state.viewDescription === subject._id ? "" : "none";
var hover = this.state.viewSummary === subject._id ? "" : "none";
var comments = this.state.comments;
var subjectAuthor = this.state.name;
return (
<div key={subject._id}>
<div className="subjectTitle">
<p
className="title"
onClick={() => this.clickHandler(subject._id)}
onMouseEnter={() => this.hoverHandler(subject._id)}
onMouseLeave={() => this.hoverOffHandler()}
>
{subject.title}
</p>
<p className="rate">
Rate this subject:
<button onClick={() => this.rateHandler(subject._id, 1)}>
1
</button>
<button onClick={() => this.rateHandler(subject._id, 2)}>
2
</button>
<button onClick={() => this.rateHandler(subject._id, 3)}>
3
</button>
<button onClick={() => this.rateHandler(subject._id, 4)}>
4
</button>
<button onClick={() => this.rateHandler(subject._id, 5)}>
5
</button>
</p>
<p className="rating">
Rating: {(subject.rating / subject.noOfVotes).toFixed(1)}/5
</p>
<p className="summary" style={{ display: hover }}>
{subject.summary}
</p>
</div>
<div className="subjectBody " style={{ display: view }}>
<div className="subjectAuthor">
<p className="author">
Subject created by: {subjectAuthor}
<br /> {subject.date}
</p>
</div>
<div className="subjectDescription">
<p className="description">{subject.description}</p>
</div>
<div className="subjectLinks">Links:</div>
<div className="subjectComments">
<p style={{ fontWeight: "bold" }}>Comments:</p>
{comments.map((comment, i) => {
return (
<div key={i} className="singleComment">
<p>
{comment.title}
<br />
{comment.comment}
<br />
Comment by : {comment.author}
</p>
</div>
);
})}
<a href="/addcomment">
<div className="buttonAddComment">ADD COMMENT</div>
</a>
</div>
</div>
</div>
);
});
return (
<div id="Subject">
<GoogleSearch />
{subjectItems}
</div>
);
}
}
Subject.propTypes = {
fetchSubjects: PropTypes.func.isRequired,
fetchComments: PropTypes.func.isRequired,
updateSubject: PropTypes.func.isRequired,
getUser: PropTypes.func.isRequired,
subjects: PropTypes.array.isRequired,
comments: PropTypes.array.isRequired,
newPost: PropTypes.object,
subAuthor: PropTypes.object,
};
const mapStateToProps = (state) => ({
subjects: state.subjects.items,
newSubject: state.subjects.item,
comments: state.comments.items,
newComment: state.comments.item,
subAuthor: state.auth.tempUser[0],
});
// export default Subject;
export default connect(mapStateToProps, {
fetchSubjects,
fetchComments,
updateSubject, // rate subject
getUser, // used for getting author name
})(Subject, Comment);
import React,{Component}来自“React”;
从“道具类型”导入道具类型;
从“/GoogleSearch”导入GoogleSearch;
从“react redux”导入{connect};
从“../../actions/subject”导入{fetchSubjects}”;
从“../../actions/comment”导入{fetchComments};
从“../../actions/subject”导入{updateSubject}”;
从“../../actions/authActions”导入{getUser};
类主题扩展组件{
//关于加载主题和注释
//是从数据库中提取的
componentDidMount(){
this.props.fetchSubjects();
this.props.fetchComments();
}
建造师(道具){
超级(道具);
此.state={
//为主题设置初始状态
//说明、摘要和评论均不可见
视图描述:-1,
视图摘要:-1,
评论:[],
姓名:“,
};
}
组件将接收道具(下一步){
//新主题和评论添加到顶部
//阵列的
如果(nextrops.newPost){
this.props.subjects.unshift(nextrops.newPost);
}
如果(nextrops.newPost){
this.props.comments.unshift(nextrops.newPost);
}
}
clickHandler=(id)=>{
//单击主题标题时,传入其id
//并使描述和注释可见
const{viewsdescription}=this.state;
this.setState({viewscription:viewscription==id?-1:id});
//向州政府添加相关评论
var i;
var-temp=[];
对于(i=0;i{
this.setState({viewSummary:id});
};
hoverOffHandler=()=>{
this.setState({viewSummary:-1});
};
rateHandler=(id,rate)=>{
const subject=this.props.subjects.find((subject)=>subject.\u id==id);
//如果未找到主题,则不会调用updateSubject
主题&&
this.props.updateSubject(id、rate、subject.noOfVotes、subject.rating);
警惕(“谢谢你给这个主题打分。”);
};
//接受主体的id
//在道具中找到它
//获取其作者id
//调用传递作者id的getUser
芬达托尔(id){
log(“命中findautor函数”);
const subject=this.props.subjects.find((subject)=>subject.\u id==id);
const authorId=subject.author;
console.log(authord);
this.props.getUser(authorId);
}
render(){
const subjectItems=this.props.subjects.map((subject)=>{
//如果状态等于设置为可见(如果未设置为不可见)的id
var view=this.state.viewsdescription==subject.\u id?“:“无”;
var hover=this.state.viewSummary==subject.\u id?“:“无”;
var注释=this.state.comments;
var subjectAuthor=this.state.name;
返回(
this.clickHandler(subject.\u id)}
onMouseCenter={()=>this.hoverHandler(subject.\u id)}
onMouseLeave={()=>this.hoverOffHandler()}
>
{subject.title}
对该主题进行评分:
this.rateHandler(subject.\u id,1)}>
1.
this.rateHandler(subject.\u id,2)}>
2.
this.rateHandler(subject.\u id,3)}>
3.
this.rateHandler(subject.\u id,4)}>
4.
this.rateHandler(subject.\u id,5)}>
5.
评级:{(subject.Rating/subject.noOfVotes.toFixed(1)}/5
{主题摘要}
主题创建人:{subjectAuthor}
{subject.date}
{subject.description}
链接:
注释:
{comments.map((comment,i)=>{
返回(
{comment.title}
{comment.comment}
评论人:{Comment.author}
);
})}
);
});
返回(
{subjectItems}
);
}
}
Subject.propTypes={
fetchSubjects:PropTypes.func.isRequired,
fetchComments:PropTypes。