简体   繁体   中英

Why doesn't my state update in React.js

I don't understand why my state isn't updating in this code. I reviewed an answer here but doesn't seem to answer my question b/c I only have one component to bind to.

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    constructor() {
        super();
        this.state={
            headline: 'this is headline state',
            cat: 25
        }
    }

    update(e) {
        this.setState=({headline: e.target.value})
    }

    render() {
        let headline=this.state.headline
        return (
            <div>
                <input type="text"
                onChange={this.update.bind(this)} />
                <h1>{headline}</h1>
            </div>
        );
    }
}

App.propTypes = {
    headline: React.PropTypes.string,
    cat: React.PropTypes.number
}

ReactDOM.render(
    <App />,
    document.getElementById('app')
    );

setState is method not property, remove =

update(e) {
   this.setState({ headline: e.target.value });
}

Example

There is a type in your code:

this.setState=({headline: e.target.value})

Should be

this.setState({headline: e.target.value})

The rest looks fine.

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