我正在尝试更新反应js中的状态。直接状态突变正在更新状态,但设置状态不起作用,为什么?
此更新
var arrNew = [{ name: "hasan ", age: 645 }, { name: "hasan ", age: 64 }, { name: "hasan ", age: 6} ];
console.log("old state ----> ", this.state.arr)
this.state.arr = arrNew ;
console.log("new state ----> ",this.state.arr)
这没有做任何事......?
this.setState({
arr: [...this.state.arr, arrNew]
})
这是我的完整代码.......................................... .................................................. .................................................. .................................................. .................................................. .................................................. .................................
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props);
this.state = { arr : [] , show : false }
}
handleChange = () => {
var arrNew = [{ name: "hasan ", age: 645 }, { name: "hasan ", age: 64 }, { name: "hasan ", age: 6} ];
console.log("old state ----> ", this.state.arr)
this.setState({
arr: [...this.state.arr, arrNew],
show: true,
})
console.log("new state ----> ",this.state.arr)
}
render() {
return (
<div className="App">
<button onClick= { this.handleChange } > Get Data </button>
<div id= "show">
{
this.state.show ? ( this.state.arr.map( data => {
<ul>
<li> data.name </li>
<li> data.age </li>
</ul>
})) : null
}
</div>
</div>
);
}
}
export default App;
答案 0 :(得分:2)
我修复了你传递给map方法的回调(因为你正在使用大括号返回undefined)并传播arrNew的项目并且它有效。也许你的代码无声地失败
class App extends React.Component {
constructor(props){
super(props);
this.state = { arr : [] , show : false }
}
handleChange = () => {
var arrNew = [{ name: "hasan ", age: 645 }, { name: "hasan ", age: 64 }, { name: "hasan ", age: 6} ];
//console.log("old state ----> ", this.state.arr)
this.setState({
arr: [...this.state.arr, ...arrNew],
show : true
})
//console.log("new state ----> ",this.state.arr)
}
render() {
console.log(this.state)
const { arr, show } = this.state;
return (
<div className="App">
<button onClick= { this.handleChange } > Get Data </button>
<div id="show">
{
this.state.show ? (this.state.arr.map((data, i)=> (
<ul key={i}>
<li> {data.name} </li>
<li> {data.age} </li>
</ul>
))) : null
}
</div>
</div>
);
}
}
ReactDOM.render(
<App/>,
document.querySelector('#root')
);
工作demo
答案 1 :(得分:0)
@ shahin-hasan,您可以使用以下内容:
import React, {Component} from 'react';
import './App.css';
import update from 'immutability-helper';
class App extends Component {
constructor(props) {
super(props);
this.state = {arr: []};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
debugger;
var arrNew = [{name: "hasan ", age: 645}, {name: "hasan ", age: 64}, {name: "hasan ", age: 6}];
const tmp = update(this.state.arr, {$push: arrNew});
this.setState({
arr: tmp
})
}
render() {
console.log(this.state);
return (
<div>
<input type="button" value={this.props.formName} onClick={this.handleClick}/>
</div>
);
}
}
export default App;