如何从任何组件外部调用 React 的 setState 函数,例如实用程序函数? [英] How call React's setState function from outside of any component, like a utility function?

查看:36
本文介绍了如何从任何组件外部调用 React 的 setState 函数,例如实用程序函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我想将读取、写入操作移动到实用程序文件,即远离组件.我正在尝试这样做.

I have an app where I want to move the read, write operations to a utility file i.e. away from component. I am trying to do it this way.

component.js

component.js

import { saveData } from './utils/fileSave.js';

class App extends Component {
    saveContent() {
        saveData(this.setState, data);
    }
    ...
}

utils/fileSave.js

utils/fileSave.js

const saveData = (setState, data) => {
    setState(data);
}

然而,这会导致一个错误,说'TypeError: Cannot read property 'updater' of undefined'

However, that leads to an error, saying 'TypeError: Cannot read property 'updater' of undefined'

不确定这是否是正确的方法.

Not sure if this is the correct way to go about it.

推荐答案

看起来你需要先绑定 setState 才能将它传递给外部函数.

It looks like you need to bind setState before passing it to an external function.

saveData(this.setState.bind(this), data);

这篇关于如何从任何组件外部调用 React 的 setState 函数,例如实用程序函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆