Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

reactjs - componentDidMount not changing state for array variable but it works if changed to int instead of array

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
//import { collapseTextChangeRangesAcrossMultipleVersions, ImportsNotUsedAsValues } from 'typescript';
class App extends Component {
   state = {
    values: []
  }
  componentDidMount() {
   
    //console.log("Component will mount called");
    this.setState({ values: [{id:1, name:'Value 101'}] });
    //console.log(this.state.values);
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          Test
          <ul>
            {this.state.values.map((value:any)=>{
              <li>{value.name}</li>
            })}
          </ul>
          
        </header>
      </div>
    );
  }
}

export default App;

I am trying to create sample react ts application. While I try to set new values in componentDidMount the values are not changing. The behavior is same in componentWillMount, the state is not changing for values.

question from:https://stackoverflow.com/questions/65541561/componentdidmount-not-changing-state-for-array-variable-but-it-works-if-changed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

componentWillMount doesn't trigger rendering, as stated in the documentation.

However, you can change state in componentDidMount, which will result in rendering your component twice.

Moreover, you should probably replace

{this.state.values.map((value:any)=>{
    <li>{value.name}</li>
})}

with

{
    this.state.values.map((value: any, index: number) => {
        return <li key={index}>{value.name}</li>)
    }
}

as your current piece of code doesn't return a JSX object. Finally, try to use a real key instead of index.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...