无法设置然后修改组件的状态

时间:2018-12-06 19:58:41

标签: javascript reactjs

我已经阅读了类似的错误消息,但是区别是大多数错误消息都围绕事件绑定。

我收到此错误:Cannot read property 'setState' of undefined 我在this.setState(state => {

上收到错误消息

在尝试使用该代码之前,我只是尝试使用this.state.finalText = translation;

无论如何我都无法在没有状态错误的情况下呈现翻译后的文本。

这是我第二天与react一起工作,因此很好的解释将不胜感激。

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;

1 个答案:

答案 0 :(得分:3)

您的问题似乎是this。如果将回调从function...更改为箭头函数() => ...,则this将绑定到包围的词法上下文的this而不是执行上下文的this。解决方法:

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