最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Array contents not rendering in ReactJS - Stack Overflow

matteradmin5PV0评论

I am still fairly new to React. I am trying to map the contents of an array in ReactJS. Currently, I am having no results render. Here is the section of code I am using to map the array contents:

return (
        <div>
            {this.state.errors.map( (error, index) => 
                <div key={index} className="alert alert-danger" role="alert">
                    {error}
                </div>
            )}
        </div>
       )

Here is how I am initializing the state:

this.state = {
    workoutId:'',
    daysOfWeek:[],
    name:'',
    trainingPlan:'',
    errors: []
}

And here is where I am populating the errors array:

if(this.state.daysOfWeek.length < 1) {
    this.state.errors.push('Must select at least 1 day to perform workout');
}
if(this.state.workoutId === '') {
    this.state.errors.push('Please select a workout to edit');
}

console.log(this.state.errors);

I am seeing that the array is being populated with those strings on the console.log. My understanding of React is that the ponent will re-render itself when changes are made. Is that correct? Anyway, can someone explain to me why my array contents will not render? I have tried mapping based on if the length of the errors array is greater than 0, which did not work either.

I am still fairly new to React. I am trying to map the contents of an array in ReactJS. Currently, I am having no results render. Here is the section of code I am using to map the array contents:

return (
        <div>
            {this.state.errors.map( (error, index) => 
                <div key={index} className="alert alert-danger" role="alert">
                    {error}
                </div>
            )}
        </div>
       )

Here is how I am initializing the state:

this.state = {
    workoutId:'',
    daysOfWeek:[],
    name:'',
    trainingPlan:'',
    errors: []
}

And here is where I am populating the errors array:

if(this.state.daysOfWeek.length < 1) {
    this.state.errors.push('Must select at least 1 day to perform workout');
}
if(this.state.workoutId === '') {
    this.state.errors.push('Please select a workout to edit');
}

console.log(this.state.errors);

I am seeing that the array is being populated with those strings on the console.log. My understanding of React is that the ponent will re-render itself when changes are made. Is that correct? Anyway, can someone explain to me why my array contents will not render? I have tried mapping based on if the length of the errors array is greater than 0, which did not work either.

Share Improve this question asked Aug 12, 2018 at 18:23 Nick DNick D 331 silver badge4 bronze badges 2
  • 2 reactjs/docs/react-ponent.html#setstate – skylerfenn Commented Aug 12, 2018 at 18:25
  • You can’t manipulate the state object directly. – skylerfenn Commented Aug 12, 2018 at 18:26
Add a ment  | 

2 Answers 2

Reset to default 4

In React, you must never assign to this.state directly. Use this.setState() instead. The reason is that otherwise React would not know you had changed the state.

The only exception to this rule where you assign directly to this.state is in your ponent's constructor.

You cannot modify your state object or any of the objects it contains directly; you must instead use setState. And when you're setting state based on existing state, you must use the callback version of it; details.

So in your case, if you want to add to the existing this.state.errors array, then:

let errors = [];
if(this.state.daysOfWeek.length < 1) {
    errors.push('Must select at least 1 day to perform workout');
}
if(this.state.workoutId === '') {
    errors.push('Please select a workout to edit');
}
if (errors.length) {
    this.setState(prevState => ({errors: [...prevState.errors, ...errors]}));
}

If you want to replace the this.state.errors array, you don't need the callback form:

let errors = [];
if(this.state.daysOfWeek.length < 1) {
    errors.push('Must select at least 1 day to perform workout');
}
if(this.state.workoutId === '') {
    errors.push('Please select a workout to edit');
}
if (errors.length) { // Or maybe you don't want this check and want to
                     // set it anyway, to clear existing errors
    this.setState({errors});
}
Post a comment

comment list (0)

  1. No comments so far