Reactjs:setState总是失败并在componentDidMount中返回undefined

dee*_*eek 2 javascript ecmascript-6 reactjs

使用setState()有奇怪的错误,我总是没有设置为state:

错误代码:

TypeError:无法读取undefined(...)的属性'setState'

class HelloWorld extends React.Component {
constructor() {
    super();
    this.state = {listings:[]};
};

componentDidMount (){
    fetch('./javascripts/data.json').then(function(response) {
        return response.json()
    }).then(function(json) {
       console.log('parsed json ', json.listings);
        this.setState({listings: 'test string'});
    }).catch((error) => {
        console.log(error);
    })
}
render () {
    return (
        <ListingUser userData={this.state.listings} />
    );
}
}

    ReactDOM.render(
        <HelloWorld />,
        document.getElementById('example')
    );
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 9

您收到此错误的原因是因为this未在promise中引用您的组件类.为了使用this.setState(),您需要绑定正确的上下文this.

fetch('./javascripts/data.json')
    .then(function(response) {
        return response.json();
    })
    .then(function(json) {
        console.log('parsed json ', json.listings);
        this.setState({listings: 'test string'});
    }.bind(this))
    .catch((error) => {
        console.log(error);
    });
Run Code Online (Sandbox Code Playgroud)

您还可以使用箭头函数,它将在词法上绑定正确的值this.

fetch('./javascripts/data.json')
    .then(response => {
        return response.json();
    })
    .then(json => {
        console.log('parsed json ', json.listings);
        this.setState({listings: 'test string'});
    })
    .catch(error => {
        console.log(error);
    });
Run Code Online (Sandbox Code Playgroud)