【发布时间】:2019-04-27 07:27:56
【问题描述】:
我有 2 个组件。不是亲子。 一个组件的状态由 Redux 管理。 第二个组件有一个按钮。 如何通过单击第二个组件中的按钮来启动第一个组件状态更改?
【问题讨论】:
-
Redux 正是为此而生的。连接第二个组件并将更改分发到存储。
标签: reactjs redux components state
我有 2 个组件。不是亲子。 一个组件的状态由 Redux 管理。 第二个组件有一个按钮。 如何通过单击第二个组件中的按钮来启动第一个组件状态更改?
【问题讨论】:
标签: reactjs redux components state
以下是您要求的解决方案,其中一个组件 (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
希望这会有所帮助。如果您有任何疑问,请随时询问:)
【讨论】: