【问题标题】:Using a single component multiple times in a single parent class in react.js在 react.js 的单个父类中多次使用单个组件
【发布时间】:2020-07-08 07:30:48
【问题描述】:
class Counter extends Component {
constructor(props) {
    super(props);
    this.state = {
        age: 10,
    };
}
handleincrement = () => {
    console.log("hy");
    this.setState((prevState) => {
        return { age: prevState.age + 1 };
    });
}
render() {
    return (
        <div>
            <button onClick={this.handleincrement}>
                counter value is {this.state.age}
            </button>
        </div>
    );
}

}

function App() {
return (
    <div>
        <Counter />
        <Counter />
    </div>
);

}

我有一个组件计数器,当我单击第一个按钮时,我在 App.js 类中使用了 2 次,它导致仅增加第一个计数器组件的状态值,反之亦然。 我的问题是,为什么这两个组件的行为彼此独立?

【问题讨论】:

  • 因为计数器组件有自己的状态。两个 Counter Child 组件意味着它们都有独立的实例和状态。

标签: javascript reactjs react-router react-component react-component-unmount


【解决方案1】:

每个组件都有其own lifecycle

为了共享同一个状态,推荐,是lifting the state up

class Counter extends React.Component {
  render() {
    return <div>{this.props.age}</div>;
  }
}

class App extends React.Component {
  state = {
    age: 0
  };

  handleincrement = () => {
    this.setState(prev => ({ age: prev.age + 1 }));
  };
  render() {
    return (
      <div>
        <button onClick={this.handleincrement}>Increase</button>
        <Counter age={this.state.age} />
        <Counter age={this.state.age} />
      </div>
    );
  }
}

为了完整起见,您也可以使用全局变量(不推荐)。

类似:

let age = 10;

class Counter extends React.Component {
  handleincrement = () => {
    age++;
    this.forceUpdate();
  };
  render() {
    return (
      <div>
        <button onClick={this.handleincrement}>counter value is {age}</button>
      </div>
    );
  }
}
const App = () => {
  return (
    <div>
      <Counter />
      <Counter />
    </div>
  );
};

【讨论】:

    【解决方案2】:

    这是因为两者都是父类 App 的独立子组件。 这不是构造函数道具或 App 类中的东西。 您正在导入这两个组件,因此它们只是单独出现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-11
      • 2019-04-27
      相关资源
      最近更新 更多