其他组件的React / Redux启动状态更改

lig*_*rey 3 components state reactjs redux

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

小智 5

下面是您要求的解决方案,其中一个组件(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 )
Run Code Online (Sandbox Code Playgroud)

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 )
Run Code Online (Sandbox Code Playgroud)

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

actions.js

const INCREMENT_ONE = 'INCREMENT_ONE'

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

export { incrementAction, INCREMENT_ONE }
Run Code Online (Sandbox Code Playgroud)

在reducer.js中,我们定义状态的默认值= 0,即初始状态。只要单击该按钮,状态就会增加1,然后在Component2中显示。

reducer.js
Run Code Online (Sandbox Code Playgroud)

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