外部函数中的setState / use State反应

Sto*_*ace 6 javascript reactjs react-native

考虑以下伪代码:

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() {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

common_functions.js

export function someFunc() {
    if(this.state.whatever) {...}
    this.setState{...}
}
Run Code Online (Sandbox Code Playgroud)

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

Ume*_*esh 5

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

在您的情况下,您可以在一个地方定义 someFunction 并将特定状态变量或整个状态传递给它。在 someFunction 中完成后,返回修改后的状态并使用 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});
    }
Run Code Online (Sandbox Code Playgroud)