【问题标题】:React/Redux Launch state change of another componentReact/Redux Launch 另一个组件的状态变化
【发布时间】:2019-04-27 07:27:56
【问题描述】:

我有 2 个组件。不是亲子。 一个组件的状态由 Redux 管理。 第二个组件有一个按钮。 如何通过单击第二个组件中的按钮来启动第一个组件状态更改?

【问题讨论】:

  • Redux 正是为此而生的。连接第二个组件并将更改分发到存储。

标签: reactjs redux components state


【解决方案1】:

以下是您要求的解决方案,其中一个组件 (Component1) 有一个更改状态的按钮,而第二个组件 (Component2) 吸收这些更改。

这里的 Component1 有按钮,而 Component2 显示由于按下按钮而改变的值。 Component1 的按钮通过 mapDispatchToProps 在按钮单击时调度一个动作,这反过来将状态增加 1,我们使用 mapStateToProps 在 Component2 中检索。

Component1.jsx

import React, { Component } from 'react'
import { connect } from 'react-redux'

import { incrementAction } from './actions/action'
import Component2 from './Component2'

class Component1 extends Component {  
   render() {
     return (
       <div>
        <Component2/>
        <button onClick = { this.props.increment }> Increase </button>
      </div>
     )
   }
}

const mapDispatchToProps = dispatch => ( {
  increment: () => dispatch( incrementAction() )
} )
const mapStateToProps = ( state ) => ( {
  value: state
} )
export default connect( mapStateToProps, mapDispatchToProps )( Component1 )

Component2.jsx

import React, { Component } from 'react'
import { connect } from 'react-redux'

class Component2 extends Component {
  render() {
    const { value } = this.props
    return (
      <h1> { value } </h1>
    )
  }
}

const mapStateToProps = ( state ) => ( {
  value: state
} )

export default connect( mapStateToProps, null )( Component2 )

在actions.js中,我们定义了一个动作类型为INCREMENT_ONE的动作

actions.js

const INCREMENT_ONE = 'INCREMENT_ONE'

const incrementAction = () => ( { type: INCREMENT_ONE } )

export { incrementAction, INCREMENT_ONE }

在 reducer.js 中,我们定义了 state = 0 的默认值,即初始状态。每当单击按钮时,状态都会增加 1,然后显示在 Component2 中。

reducer.js

import { INCREMENT_ONE } from '../actions/action'

const incrementReducer = ( state = 0, action ) => {
  switch ( action.type ) {
    case INCREMENT_ONE: return state + 1
    default: return state 
  }
}

export default incrementReducer

希望这会有所帮助。如果您有任何疑问,请随时询问:)

【讨论】:

  • 感谢您的回答。在您的示例中,Component2 是 Component1 的子级。我们可以对位于 Component1 容器之外的 Component2 做同样的事情吗?
  • 嘿,当然。我将 Component2 作为 Component1 的子项的唯一原因是为了使示例更短更简单。 Component2 只是访问存储以检索最新状态。换句话说,这可以从任何地方完成,即状态访问容器(此处为 Component2)不必是调度操作的容器(此处为 Component1)的子级。
  • 再次感谢。这对我帮助很大!
  • 嗨 Vayam,现在如果组件 2 更改了状态,我如何在 Component1 中跟踪它。我试图把这段代码放在 Component1 的 mapStateToProps = (state) => { return { dialogChange: state.dialogComponent } } 问题是 Component 1 正在接收旧的 props/state
猜你喜欢
  • 2019-02-01
  • 2017-08-03
  • 2016-10-02
  • 1970-01-01
  • 2018-11-16
  • 2023-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多