javascript - React : _this2. setState 不是函数

标签 javascript reactjs

我正在使用 React 开发语音控制的幻灯片放映(幻灯片是 iframe)。我有一个工作版本(它将循环播放幻灯片,用于转到上一张/下一张幻灯片的语音命令......)但是当我尝试添加一个命令来暂停幻灯片放映循环时,我收到以下错误。我的“下一张幻灯片”命令有效并且与“暂停循环”命令没有任何不同,所以我不明白为什么“暂停循环”命令会产生错误。

这是我的第一个 React 应用程序,我们将不胜感激。

错误:

Unhandled Rejection (TypeError): _this2.setState is not a function

   | .then(res => res.json())
   | .then(
   |    (result) => {
>  |        this.setState({
   |            speechRecogStatus: result.speech_recog_status
   |        });

代码:

这只是部分代码,已被修改以删除不相关的行。

在 App.js 中

import nextSlideCommand from './commands/next-slide';
import pauseLoopCommand from './commands/pause-loop';
import SlideList from './slide-list.json';

class App extends Component {
    constructor(props) {
        super(props);

        this.fetchingMasterSwitchStatus = false;

        let initialSlideKeyword = SlideList.loop[0].keyword;

        this.state = {
            speechRecogStatus: "off",
            iframeSrc: SlideList.list[initialSlideKeyword].url,
            pageTitle: SlideList.list[initialSlideKeyword].title,
            loopIndex: 0,
            loopIsPlaying: true,
            iframeStyle: {visibility: 'hidden'},
        };

        if (annyang) {

            // define voice commands
            let commands = {
                'next slide': () => {
                    nextSlideCommand.call(this, SlideList);
                },
                'pause loop': () => {
                    pauseLoopCommand.call(this, SlideList);
                },
            };

            // Add our commands to annyang
            annyang.addCommands(commands);
        }

        // suggested by another StackOverflow post on 
        // this error - doesn't solve my problem
        this.getMasterSwitchStatus = this.getMasterSwitchStatus.bind(this);
        this.iframeOnLoad = this.iframeOnLoad.bind(this);
    }

    getMasterSwitchStatus() {

        // query an online JSON file periodically to determine whether this 
        // app should be listening for voice commands or not

        if (this.fetchingMasterSwitchStatus) return;

        this.fetchingMasterSwitchStatus = true;
        fetch("JSON_URL")
            .then(res => res.json())
            .then(
                (result) => {
                    this.setState({
                        speechRecogStatus: result.speech_recog_status
                    });

                    let status = (annyang.isListening()) ? "on" : "off";
                    if (status === result.speech_recog_status) {
                        this.fetchingMasterSwitchStatus = false;
                        return;
                    }

                    if (result.speech_recog_status === 'on') {
                        annyang.resume();
                    } else {
                        annyang.abort();
                    }
                    this.fetchingMasterSwitchStatus = false;
                },
                (error) => {
                    this.fetchingMasterSwitchStatus = false;
                }
            );
    }

    componentDidMount() {
        setInterval(
            () => {
                this.getMasterSwitchStatus();
            },
            CHECK_MASTERSWTICH_FREQ
        );
    }

    iframeOnLoad() {
        this.setState({
            iframeStyle: {visibility: 'visible'}
        });

        setTimeout(
            () => {
                if (!this.state.loopIsPlaying) return;
                utilFunctions.nextSlide(this, SlideList)
            },
            SlideList.loop[this.state.loopIndex].dwell * 1000
        );
    }

    render() {
        return [
            <div key="content" className="content">
                <Iframe key="iframe" src={this.state.iframeSrc} 
                        iframeStyle={this.state.iframeStyle}
                        onLoadFun={() => this.iframeOnLoad()}/>
            </div>
        ];
    }

}

export default App;

commands/pause-loop.js

let pauseLoopCommand = function(SlideList) {
    this.setState = ({
        loopIsPlaying: false
    });
};

export default pauseLoopCommand;

在 commands/next-slide.js 中

let nextSlideCommand = function(SlideList) {
    // calculate new loop index
    let index = context.state.loopIndex;
    index++;
    if (index > SlideList.loop.length - 1) {
        index = 0;
    }
    let keywords = SlideList.loop[index].keyword;

    // ok, change slide
    this.setState({
        loopIndex: index,
        iframeSrc: SlideList.list[keywords].url,
        pageTitle: SlideList.list[keywords].title,
        iframeStyle: {visibility: 'hidden'},
    });
};

export default nextSlideCommand;

最佳答案

您的 pauseLoopCommand 函数正在为 this.setState 分配一个新值,因此以后的 this.setState 调用将尝试调用这个新对象作为一个函数,这将导致您的错误。

如果您像在所有其他地方那样调用函数,错误应该会消失。

let pauseLoopCommand = function(SlideList) {
    this.setState({
        loopIsPlaying: false
    });
};

export default pauseLoopCommand;

关于javascript - React : _this2. setState 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51199022/

相关文章:

javascript - Jquery ajax 成功后获取字符串

javascript - react JS : Component Not Exported

javascript - 长轮询如何工作javascript?

performance - React 组件隐藏还是重新创建?

reactjs - React 文件输入只工作一次

javascript - jQuery Mobile 页面功能

javascript - 有没有一种方法可以多次要求一个文件作为不同的模块

node.js - React应用程序中的操作响应状态代码

javascript - ReactJs - 如何防止用户篡改/修改客户端代码中的相等性检查

reactjs - 使用备用路由配置 React Router 重定向