我一直在搞乱这个时间太长了,我想不通为什么文件不被添加到本地状态。下面的代码:
onFileSelect(event){
console.log(event.target.files[0]);
let name = event.target.files[0].name;
let photoObject = event.target.files[0];
console.log(photoObject);
this.setState({ photoName: name, photo: photoObject }, function () {
console.log('from state:' + JSON.stringify(this.state.photo));
console.log('state is; ' + JSON.stringify(this.state));
});
}
而这里的文件输入:
<div className="custom-file">
<input
type="file"
className="custom-file-input"
onChange={this.onFileSelect}
id="customFile"
/>
<label className="custom-file-label" for="customFile">
{this.state.photoName}
</label>
</div>
在执行console.log的在回调的setState,我得到:
从状态:{}
状态是; { “yardName”: “请”, “yardLat”: “”, “yardLng”: “”, “yardType”: “常规”, “photoName”: “splash.jpg”, “照片”:{},“错误“:{}}
任何帮助是极大的赞赏。
我认为这个问题是你滥用this
。
this.setState({photoName:name,photo:photoObject},
function(){
console.log('from state:' + JSON.stringify(this.state.photo));
console.log('state is; ' + JSON.stringify(this.state));
})
在执行console.log功能,this
指函数本身。所以,你应该用箭头功能类似下面
this.setState({photoName:name,photo:photoObject},
() => {
console.log('from state:' + JSON.stringify(this.state.photo));
console.log('state is; ' + JSON.stringify(this.state));
})
因为在代码中的setState回调函数是有规律的功能,你可以没有这种可里面,从而@Conan李提到要么你需要改变它Arrow功能或绑定功能,有此背景下可访问的更新状态
使用.bind(本)如下面结合功能
onFileSelect(event){
console.log(event.target.files[0]);
let name = event.target.files[0].name;
let photoObject = event.target.files[0];
console.log(photoObject);
this.setState({ photoName: name, photo: photoObject }, function () {
console.log('from state:' + JSON.stringify(this.state.photo));
console.log('state is; ' + JSON.stringify(this.state));
}.bind(this)}
}