简体   繁体   中英

react this.setState isn't updated state

I'm trying to figure out why a call to this.setState isn't updating state.

I have the following lines method:

changeState(state, value){
        this.setState({state:value}, ()=>console.log(this.state));
    }

There are a few function using this, but one is a file upload component. Its a simple component that either renders a file input OR it renders an iframe, disabled input, and button. When the button is clicked I want to change the state in the parent component which then rerenders the file component and shows a file picker.

The call to this.setState seems to work ok, but when I console log state after it runs or if I stop execution before the next render takes place state is unaffected. My file upload component has a method like this:

renderField(field){
        if(this.props.hasOwnProperty('file') && this.props.file){
            return(
                <div>
                    <iframe src={this.props.file} frameborder="0"> </iframe>
                    <input
                        disabled
                        placeholder={this.props.file}
                        name={field.name}
                        type='text'
                    />
                    <span onClick={()=>this.props.changeFile(this.props.file_type, null)}>&times; Remove</span>
                </div>
            )
        }else{
            return(
                <input
                    {...field}
                    type={field.type}
                    name={field.name}
                    onChange={(event) =>{
                        field.input.onChange(field.input.value = event.target.files[0])}
                    }
                />
            )
        }
    }

when I call the method I get this output: 在此处输入图片说明

however after console logging my state is anything but changed: 在此处输入图片说明

You don't want to set the state property in your state, but the property name that state contains.

You can use a computed property name for this.

changeState(state, value) {
  this.setState({ [state]: value }, () => console.log(this.state));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM