外部函数中的 setState/use State 反应 [英] setState/use State in external function react

查看:50
本文介绍了外部函数中的 setState/use State 反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个伪代码:

component.js

...
import {someFunc} from "./common_functions.js"

export default class MyComp extends Component {
    constructor(props) {
        super(props);

    this.someFunc = someFunc.bind(this);

    this.state = {...};
    }

    _anotherFunc = () = > {
        ....
        this.someFunc();
    }

    render() {
        ...
    }
}

common_functions.js

export function someFunc() {
    if(this.state.whatever) {...}
    this.setState{...}
}

如何将函数 someFunc() 绑定到 Component 的上下文?我在各种组件中使用它,因此将它们收集在一个文件中是有意义的.现在,我收到错误无法读取任何未定义的内容".this 的上下文未知...

How would I bind the function someFunc() to the context of the Component? I use it in various Components, so it makes sense to collect them in one file. Right now, I get the error "Cannot read whatever of undefined". The context of this is unknown...

推荐答案

您不能在组件外部设置状态,因为它是组件的本地状态.如果您需要更新共享的状态,请创建一个存储(redux 存储).

You can't setState outside of the component because it is component's local state. If you need to update state which is shared, create a store (redux store).

在您的情况下,您可以在一个地方定义 someFunction 并将特定状态变量或整个状态传递给它.在 someFunction 中完成后,返回修改后的状态并使用 setState 在您的组件中更新它.

In your case, you can define someFunction at one place and pass it the specific state variable(s) or entire state. After you are done in someFunction, return the modified state and update it back in your component using setState.

export function someFunc(state) {
    if(state.whatever) {...}
    const newState = { ...state, newValue: whateverValue }
    return newState
}

_anotherFunc = () = > {
        ....
        const newState = this.someFunc(this.state);
       this.setState({newValue: newState});
    }

这篇关于外部函数中的 setState/use State 反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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