javascript - ReactJS,Javascript,使用状态更改的导入函数的正确方法

标签 javascript reactjs react-native react-router react-redux

我的 React 组件中有这段代码。

我需要的是重用其他文件中的一些组件和功能。

但是有些函数会更新我的状态。

我想知道实现此目标的最佳实践是什么。

MyComponent 主要:

import React, { Component, Fragment } from "react";

import { GenericFunction, GenericComponent } from "./functions.js";

class MyComponent extends Component {
  state = {
    myValueState: false
  };

  render() {
    const { myValueState } = this.state;

    return (
      <div>
        <GenericComponent
          GenericFunction={GenericFunction}
       // GenericFunction={GenericFunction.bind(this)} // -----> With this it works good, but is this a best practice?
        />
      </div>
    );
  }
}

export default MyComponent;

functions.js 文件:

export function GenericFunction(items) {
  if (items) {
    this.setState({ ...this.state, myValueState: true });
  } else {
    this.setState({ ...this.state, myValueState: false });
  }
}

GenericFunction={GenericFunction.bind(this)} 这是一个好方法吗?

我听说过 bind(this) 的问题。我错了吗?

最佳答案

如果您的目的只是绑定(bind)函数,那么您只能在构造函数中执行一次,如下所示

class MyComponent extends Component {
  constructor(){
    super();
    // bind the function only once
    this.GenericFunction = GenericFunction.bind(this)
  }
  state = {
    myValueState: false
  };

  render() {
    const { myValueState } = this.state;

    return (
      <div>
        <GenericComponent
          GenericFunction={this.GenericFunction} // And use it like this
        />
      </div>
    );
  }
}

关于javascript - ReactJS,Javascript,使用状态更改的导入函数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48306851/

相关文章:

geolocation - React-Native 地理定位中的超时和maximumAge是什么

javascript - 避免页面刷新并向 JavaScript session 添加值?

javascript - 在 react 中过滤 geojson 的最佳方法?

javascript - React-Router-dom 和 useHistory。将新 URL 推送到历史记录并更改 URL 但页面没有更改

javascript - 验证 DOM 嵌套 (...) : <tr> cannot appear as a child of <div>

javascript - 为什么这个注释在 Javascript/React 代码中作为参数传递?

javascript - react native 绑定(bind)这个未定义的函数

javascript - 我可以使用三等号来比较 JavaScript 字符串吗?

javascript - 使用 LoopBack 作为具有响应重构功能的 API 代理

javascript - js中为什么要用字母作为函数名和参数?