首页 > 解决方案 > 如何修复 1 状态差距?

问题描述

我正在练习将状态发送到子组件 - 父组件 - 另一个子组件。

我被困在我的练习中,

首先,我成功地制作了像这个 子组件这样的反应计数器

其次,我想将计数器值发送到另一个组件。我知道如何将状态发送到另一个子组件。但我坚持我的工作。

将状态发送到另一个组件

当我第一次单击 + 按钮时,它只适用于第一个孩子。然后,当我再次单击时,它也适用于另一个孩子(不匹配数字)

我该如何处理这个问题?

这是我的代码。


// This is Counter.js

class Counter extends Component {
    state = {
        counter: 0
    }

    handleIncrement = () => {
        this.setState(({ counter }) => ({
            counter: counter + 1
        }))
        this.props.handleCounter(this.state.counter)
    }

    handleDecrement = () => {
        this.setState(({counter}) => ({
            counter: counter - 1
        }))
        this.props.handleCounter(this.state.counter)
    }

    render() {
        return (
            <div>
                <h1>Counter</h1>
                <h3>{this.state.counter}</h3>
                <button onClick={this.handleIncrement}>+</button>
                <button onClick={this.handleDecrement}>-</button>
            </div>
        )
    }
}

// This is App.js file

import Counter from './components/counter';
import Sent from './components/sent'

class App extends React.Component {

  state = {
    counter: this.handleCounter
  }

  handleCounter = (counter) => {
    console.log("Received Count 1 ")
    this.setState({
      counter: counter
    })
  }

  render() {
    return (
      <div className="App">
        <Counter handleCounter={this.handleCounter} />
        <Sent result={this.state.counter} />
      </div>
    );
  }

}
// This is Sent.js file 
import React, { Component } from 'react'

class Sent extends React.Component {

    render() {
        return (
            <div>
                <h2>Result ==> {this.props.result}</h2>
            </div>
        )
    }
}

标签: javascriptreactjs

解决方案


推荐阅读