React 中 setState({key:value}),key是一个变量时,react会直接把它当作字符串
开始一直没发现问题所在,打印this.state.key发现值也是对的,后来发现是react直接把它当作字符串了
import React, { Component } from 'react';
import { Button } from 'antd';
class Demo extends Component {
constructor(props) {
super(props);
this.fn = this.fn.bind(this);
}
fn(key,value){
this.setState({
key:value
},()=>{
console.log(this.state.key);
})
}
render() {
return (
<div>
<Button onClick={() => this.fn('width','100px')}>设置宽度</Button>
<Button onClick={() => this.fn('height','100px')}>设置高度</Button>
</div>
);
}
}
export default Demo
其实我打印的时候也犯了错,不然会更快找出bug,这里我打印的this.state.key
,然鹅key
作为变量应该是这么写this.state[key]
,这样打印出来的应该是undefined
,会发现React将变量key
作为字符串了
然后我连蒙带猜的,这样写this.setState({[key]:value})
fn(key,value){
this.setState({
[key]:value
},()=>{
console.log(this.state);
})
}
蒙对了,解决~