React/Props/State: 无法读取 null 的属性(读取 ‘userId’)在 Function.mapStateToProps

huangapple go评论67阅读模式
英文:

React/Props/State: Uncaught TypeError: Cannot read properties of null (reading 'userId') at Function.mapStateToProps

问题

Here's the translated code part:

我有一个正在开发的博客 Web 应用程序

主题是名为Bob's Garage”的汽车修理厂。

我有一个“博客”页面,其他页面基本上与“博客”页面相同,但内容不同(例如“用户反馈页面”、“用户评论页面”等)。

“博客”页面可以正常工作,但“反馈”和“评论”页面不行。

这里是代码:

AddFeedback.js:
```javascript
// 导入所需的模块和组件
import React, { Fragment, useState } from 'react';
import PropTypes from 'prop-types';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';
import { addFeedback } from '../../actions/feedbackActions';

// 组件定义
const AddFeedback = ({ addFeedback, userId }) => {
  const [formData, setFormData] = useState({
    Author: '',
    Heading: '',
    Feedback: '',
    Location: '',
    errors: {
      body: '您必须在提供的文本框中输入您的反馈',
    },
  });

  // 其余的代码...

  return (
    <Fragment>
      {/* JSX 渲染部分 */}
    </Fragment>
  );
};

// PropTypes 部分
AddFeedback.propTypes = {
  addFeedback: PropTypes.func.isRequired,
};

// mapStateToProps 部分
const mapStateToProps = (state) => ({
  userId: state.auth.user.userId,
});

// 导出组件
export default connect(mapStateToProps, { addFeedback })(AddFeedback);

AddBlog.js:

// 导入所需的模块和组件
import React, { Fragment, useState } from 'react';
import PropTypes from 'prop-types';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';
import { addBlog } from '../../actions/blogActions';

// 组件定义
const AddBlog = ({ addBlog, userId }) => {
  const [formData, setFormData] = useState({
    Post: '',
    Author: '',
    Heading: '',
    errors: {
      Post: '您必须在提供的文本框中输入您的博客文章',
    },
  });

  // 其余的代码...

  return (
    <Fragment>
      {/* JSX 渲染部分 */}
    </Fragment>
  );
};

// PropTypes 部分
AddBlog.propTypes = {
  addBlog: PropTypes.func.isRequired,
};

// mapStateToProps 部分
const mapStateToProps = (state) => ({
  userId: state.auth.user.userId,
});

// 导出组件
export default connect(mapStateToProps, { addBlog })(AddBlog);

希望这有助于你解决问题。如果你需要更多帮助或其他源文件,请告诉我。

英文:

I have a blog webapp that I'm developing.

The theme is a car mechanic's workshop called "Bob's Garage".

I have a "blog" page, then the rest of the pages are basically the same as the "blog" page but with different content (e.g "User Feedback page". "User reviews page", etc..

The "blog" page is working, but the "feedback" and "review" page are not.

The code is virtually identical between the pages, just some different names (e.g "AddBlog()" becomes "AddFeedback()")

Here is the code:

AddFeedback.js:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//rafcp
// import fragment, useState
import React, {Fragment, useState} from &#39;react&#39;;
import PropTypes from &#39;prop-types&#39;;
// import useNavigate
import {useNavigate} from &#39;react-router-dom&#39;;
// import connect
import { connect } from &#39;react-redux&#39;;
// import our addFeedback function.
import { addFeedback} from &#39;../../actions/feedbackActions&#39;;
const AddFeedback = ({ addFeedback, userId }) =&gt; {
// Create component state.
const [formData, setFormData] = useState({
Author: &#39;&#39;,
Heading:&#39;&#39;,
Feedback:&#39;&#39;,
Location:&#39;&#39;,
errors: {
body: &#39;You must enter your feedback in the box provided&#39;
}
});
console.log(&quot;formData.body = &quot; + formData.body);  // formData.body is the user input in the textbox of the Add New Blog Entry page
// Use destructuring to pull the variables out of our state.
const { Author, Heading, Feedback, Location, errors } = formData;
// Create our navigate variable.
const navigate = useNavigate();
// on Change function.
const onChange = e =&gt; {
setFormData({
...formData, [e.target.name]: e.target.value
});
}
// Create our on submit
const onSubmit = async(e) =&gt; {
e.preventDefault();
// Test that the onSubmit is called.
console.log(&#39;Onsumbit - Add running...&#39;);
// Check for errors / validation.
if( Feedback === &#39;&#39; || Feedback === undefined){
console.log(&#39;feedback empty&#39;);
// Save an error message to the state using the errors object.
// remember that we also need to include everything that is in the state.
setFormData({
...formData,
errors:{
body: &#39;You must enter feedback in the box above&#39;,
Heading: &#39;You must enter your heading in the box above&#39;,
Author: &#39;You must enter your name in the box above&#39;,
Feedback: &#39;You must enter your feedback in the box above&#39;,
Location: &#39;You must enter your location in the box above&#39;
}
});
// stop the onSubmit running.
return;
} else {
setFormData({
...formData,
errors:{
Author: &#39;&#39;,
Heading: &#39;&#39;,
Feedback: &#39;&#39;,
Location: &#39;&#39;,
body: &#39;&#39;
}
});
}
let publishDate = new Date();
let publishDay = publishDate.getDate();
let publishMonth = publishDate.getMonth() + 1;
let publishYear = publishDate.getFullYear();
console.log(&quot;AddFeedback.js: userId = &quot; + userId);
// create a newItem to add to our feedback list.
const newItem = {
Author: Author,
Heading: Heading,
Feedback: Feedback,
PublishDate: publishYear + &quot;-&quot; + publishMonth + &quot;-&quot; + publishDay,
Location: Location,
Id: userId,
UserUserId: userId 
//UserUserId: userUserId     
//UserUserId:auth.user.userId
}
console.log(newItem);
// Send our newItem to an API or state managemeht system.
// Call our addFeedback function.
addFeedback(newItem);
// We can do other things after this, like redirect the browser.
navigate(&#39;/feedback&#39;);
}; // end of onSubmit.
return (
&lt;Fragment&gt;
&lt;h2 className=&#39;text-primary&#39;&gt;Add New Feedback&lt;/h2&gt;
&lt;div className=&#39;card mb-3&#39;&gt;
&lt;div className=&#39;card-header&#39;&gt;
Add Your Feedback
&lt;/div&gt;
&lt;div className=&#39;card-body&#39;&gt;
&lt;form onSubmit={e =&gt; onSubmit(e)}&gt;
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Heading:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.heading ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;heading&#39;
placeholder=&#39;Your Heading&#39;
name=&#39;Heading&#39;
value={Heading}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.heading &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.heading}
&lt;/div&gt;}
&lt;/div&gt;
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Author:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.heading ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;author&#39;
placeholder=&#39;Author&#39;
name=&#39;Author&#39;
value={Author}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.heading &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.heading}
&lt;/div&gt;}
&lt;/div&gt;
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Location:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.heading ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;location&#39;
placeholder=&#39;Location&#39;
name=&#39;Location&#39;
value={Location}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.heading &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.heading}
&lt;/div&gt;}
&lt;/div&gt;
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Have your say below:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.body ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;feedback&#39;
placeholder=&#39;Your Feedback&#39;
name=&#39;Feedback&#39;
value={Feedback}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.body &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.body}
&lt;/div&gt;}
&lt;/div&gt;
{/*  &lt;div className=&#39;mb-3&#39;&gt;
//   &lt;label htmlFor=&#39;name&#39;&gt;Name&lt;/label&gt;
//   &lt;input 
//     type=&#39;text&#39;
//     className=&#39;form-control&#39;
//     id=&#39;name&#39;
//     placeholder=&#39;Name&#39;
//     name=&#39;name&#39;
//     value={name} 
//     onChange={e =&gt; onChange(e)}
//   /&gt;
&lt;/div&gt; */}
{/* &lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;image&#39;&gt;Image&lt;/label&gt;
&lt;input 
type=&#39;text&#39;
className=&#39;form-control&#39;
id=&#39;image&#39;
placeholder=&#39;URL for image&#39;
name=&#39;image&#39;
value={image} 
onChange={e =&gt; onChange(e)}
/&gt;
&lt;/div&gt; */}
&lt;div className=&#39;d-grid gap-2&#39;&gt;
&lt;input type=&#39;submit&#39; value=&#39;Add Feedback&#39; className=&#39;btn btn-light &#39;/&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/Fragment&gt;
)
}
// Proptypes
AddFeedback.propTypes = {
addFeedback: PropTypes.func.isRequired
}
//mapState to props
//user from state(auth)
//get the user id of the person logged in
//auth.user
//auth.user.userId
//pass that userId through in onSubmit function
const mapStateToProps = state =&gt; ({
userId: state.auth.user.userId
})
// add in connect.
// We do not need anything from the state or store. 
// that means null, as we do not need mapState to props.
export default connect(mapStateToProps, {addFeedback})(AddFeedback)

<!-- end snippet -->

AddBlog.js:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

//rafcp
// import fragment, useState
import React, {Fragment, useState} from &#39;react&#39;;
import PropTypes from &#39;prop-types&#39;;
// import useNavigate
import {useNavigate} from &#39;react-router-dom&#39;;
// import connect
import { connect } from &#39;react-redux&#39;;
// import our addFeedback function.
import { addBlog} from &#39;../../actions/blogActions&#39;;
const AddBlog = ({ addBlog, userId }) =&gt; {
// Create component state.
const [formData, setFormData] = useState({
//Post: &#39;&#39;,
//Author: &#39;&#39;,
Heading: &#39;&#39;,
errors: {
Post: &#39;You must enter your blog post in the box provided&#39;
}
});
console.log(&quot;formData.Post = &quot; + formData.Post);  // formData.Post is the user input in the textbox of the Add New Blog Entry page
// Use destructuring to pull the variables out of our state.
const { Post, Author, ImageURL, errors, Heading } = formData;
// Create our navigate variable.
const navigate = useNavigate();
// on Change function.
const onChange = e =&gt; {
setFormData({
...formData, [e.target.name]: e.target.value
});
}
// Create our on submit
const onSubmit = async(e) =&gt; {
e.preventDefault();
// Test that the onSubmit is called.
console.log(&#39;Onsumbit - Add running...&#39;);
// Check for errors / validation.
if( Post === &#39;&#39; || Post === undefined){
console.log(&#39;post empty&#39;);
// Save an error message to the state using the errors object.
// remember that we also need to include everything that is in the state.
setFormData({
...formData,
errors:{
Post: &#39;You must enter blog entry in the box above&#39;
}
});
// stop the onSubmit running.
return;
} else {
setFormData({
...formData,
errors:{
Post: &#39;&#39;
}
});
}
let publishDate = new Date();
let publishDay = publishDate.getDate();
let publishMonth = publishDate.getMonth() + 1;
let publishYear = publishDate.getFullYear();
console.log(&quot;AddBlog.js: userId = &quot; + userId);
// create a newItem to add to our feedback list.
const newItem = {
Post: Post,
Author: Author,
Heading: Heading,
ImageURL: ImageURL,
PublishDate: publishYear + &quot;-&quot; + publishMonth + &quot;-&quot; + publishDay, // create function
UserUserId: userId 
//UserUserId: userUserId     
//UserUserId:auth.user.userId
}
console.log(newItem);
// Send our newItem to an API or state managemeht system.
// Call our addFeedback function.
addBlog(newItem);
// We can do other things after this, like redirect the browser.
navigate(&#39;/blog&#39;);
}; // end of onSubmit.
return (
&lt;Fragment&gt;
&lt;h2 className=&#39;text-primary&#39;&gt;Add New Blog Entry&lt;/h2&gt;
&lt;div className=&#39;card mb-3&#39;&gt;
&lt;div className=&#39;card-header&#39;&gt;
Add Your Blog Entry
&lt;/div&gt;
&lt;div className=&#39;card-body&#39;&gt;
&lt;form onSubmit={e =&gt; onSubmit(e)}&gt;
&lt;div className=&#39;mb-3&#39;&gt;
{/* Heading */}
&lt;label htmlFor=&#39;body&#39;&gt;Heading:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.heading ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;heading&#39;
placeholder=&#39;Your Heading&#39;
name=&#39;Heading&#39;
value={Heading}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.heading &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.heading}
&lt;/div&gt;}
&lt;/div&gt;
{/* Image URL */}
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Image URL:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.ImageURL ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;imageurl&#39;
placeholder=&#39;Your image URL&#39;
name=&#39;ImageURL&#39;
value={ImageURL}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.ImageURL &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.ImageURL}
&lt;/div&gt;}
&lt;/div&gt;
{/* Author */}
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Author:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.Author ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;author&#39;
placeholder=&#39;Your Heading&#39;
name=&#39;Author&#39;
value={Author}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.heading &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.heading}
&lt;/div&gt;}
&lt;/div&gt;
{/* Author */}
&lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;body&#39;&gt;Have your say below:&lt;/label&gt;
&lt;textarea 
className={`form-control ${errors.Post ? &quot;is-invalid&quot; : &#39;is-valid&#39;}`}
id=&#39;post&#39;
placeholder=&#39;Your Blog Post&#39;
name=&#39;Post&#39;
value={Post}
// Add in our onChange event
onChange={ e =&gt; onChange(e)}
&gt;&lt;/textarea&gt;
{errors.Post &amp;&amp; &lt;div  className=&#39;invalid-feedback&#39;&gt;
{errors.Post}
&lt;/div&gt;}
&lt;/div&gt;
{/*  &lt;div className=&#39;mb-3&#39;&gt;
//   &lt;label htmlFor=&#39;name&#39;&gt;Name&lt;/label&gt;
//   &lt;input 
//     type=&#39;text&#39;
//     className=&#39;form-control&#39;
//     id=&#39;name&#39;
//     placeholder=&#39;Name&#39;
//     name=&#39;name&#39;
//     value={name} 
//     onChange={e =&gt; onChange(e)}
//   /&gt;
&lt;/div&gt; */}
{/* &lt;div className=&#39;mb-3&#39;&gt;
&lt;label htmlFor=&#39;image&#39;&gt;Image&lt;/label&gt;
&lt;input 
type=&#39;text&#39;
className=&#39;form-control&#39;
id=&#39;image&#39;
placeholder=&#39;URL for image&#39;
name=&#39;image&#39;
value={image} 
onChange={e =&gt; onChange(e)}
/&gt;
&lt;/div&gt; */}
&lt;div className=&#39;d-grid gap-2&#39;&gt;
&lt;input type=&#39;submit&#39; value=&#39;Add Blog Entry&#39; className=&#39;btn btn-light &#39;/&gt;
&lt;/div&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/Fragment&gt;
)
}
// Proptypes
AddBlog.propTypes = {
addBlog: PropTypes.func.isRequired
}
//mapState to props
//user from state(auth)
//get the user id of the person logged in
//auth.user
//auth.user.userId
//pass that userId through in onSubmit function
const mapStateToProps = state =&gt; ({
userId: state.auth.user.userId
})
// add in connect.
// We do not need anything from the state or store. 
// that means null, as we do not need mapState to props.
export default connect(mapStateToProps, {addBlog})(AddBlog)

<!-- end snippet -->

I cannot understand why 'userId' is evaluating to 'null'...

Do any of you have any ideas as to why this error might be occurring?

Here is a screenshot of the Redux Dev Tools 'State' windows whilst on the 'AddFeedback.js' page.
React/Props/State: 无法读取 null 的属性(读取 ‘userId’)在 Function.mapStateToProps

Please let me know if you need me to post up any other source files, such as Context.js or similar.

Kind Regards,

John
Melbourne, Australia

答案1

得分: 0

我找到了解决我的问题的方法。

作为React的新手,我无意中使用了< a >标签来导航到AddFeedback.js页面,这导致状态丢失,这就是为什么userId变成了null。

所以,对于所有的React新手:

请使用React的< Link to=/your/path/here >您的链接文本< / Link>。

亲切的问候,
约翰
澳大利亚墨尔本

英文:

I found the solution to my problem.

As a React newbie I had inadvertently used an < a > tag to navigate to the AddFeedback.js page, which caused state to be lost, which is why userId became null.

So, to all you React newbies out there:

Use a React < Link to=/your/path/here > Your link text < / Link>

Kind Regards,
John
Melbourne, Australia

huangapple
  • 本文由 发表于 2023年7月13日 10:57:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76675604.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定