简体   繁体   中英

Can not set and then modify the state of component

I've read similar error messages but the difference is most of them are centered around event binding.

I get this error: Cannot read property 'setState' of undefined I get the error message on this.setState(state => {

I've tried to eliminate that, before I moved to that code I was simply using this.state.finalText = translation;

No matter what I do I can't get the translated text to render without state errors.

This is my second day working with react, so a good explanation would be highly appreciated.

import React from 'react';

class CardComponent extends React.Component {
    constructor(props) {

        super(props);
        let data = this.props.data;
        this.state = {finalText: ""};
        let truncated = data.truncated;
    }
    componentDidMount() {
        let data = this.props.data;
        let truncated = data.truncated;

        var googleTranslate = require('google-translate')('apikey');
        googleTranslate.translate(data.text, 'en', function(err, translation) {
            // by calling set state, React will know to render again
            console.log(translation);

            this.setState(state => {
                state.finalText = translation;
                return state;
              });
        });
    }

    render() {
        let data = this.props.data;
        let truncated = data.truncated;
        var test = new String(truncated);




        return (
            <div>
                <div className="card-panel grey lighten-5 z-depth-3 hoverable thin">
                    <div className="row valign-wrapper">
                        <div className="col s2">
                           {/*} <img src={data.user.profile_image_url} alt={data.user.name} className="circle responsive-img" />-*/}
                        </div>
                        <div className="col s10 left-align">
                        {(() => {
                        if (test=='true') {
                        return ( <span>ok</span>
                            //<span className="black-text"> {data.extended_tweet.full_text}</span>
                        )
                        } else {
                        return (
                            <span className="black-text">translated text: {this.state.finalText}</span>
                        )
                        }
                    })()}
                        </div>

                    </div>
                    <div className="row valign-wrapper right-align chip hoverable">
                    {/*new Date(data.created_at).toLocaleTimeString()*/}
                    </div>
                    <div className="row valign-wrapper right-align chip hoverable">
                      {/* <a href={`https://twitter.com/${data.user.screen_name}`} target="_blank">{`@${data.user.screen_name}`}</a>*/}
                    </div>
                </div>

            </div>
        );
    }
}

export default CardComponent;

Your problem seems to be this . If you change your callback from function... to an arrow function () => ... then this will be bound to the enclosing lexical context's this instead of execution context's this . So the fix:

googleTranslate.translate(data.text, 'en', (err, translation) => {
    this.setState({
        finalText: translation
    });
});

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