0
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 次,它导致仅增加第一个计数器组件的状态值,反之亦然。我的问题是,为什么这两个组件的行为彼此独立?

4

2 回答 2

1

每个组件都有自己的生命周期

对于共享相同的状态,推荐的是提升状态

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>
  );
};

编辑 Q-62789676-LiftStateUp

于 2020-07-08T07:37:58.860 回答
0

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

于 2020-07-08T07:40:09.087 回答