reactjs - 如何调度构造函数中的更改?
问题描述
我正在尝试学习 redux。我认为我的 reducer 很好,我可以从 store 中提取数据并通过 props 设置它。
但是我无法将注意力集中在操作和更改商店状态的数据上。
我有这个:
const mapDispatchToProps = (dispatch) => {
return{
what goes in here?
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ComponentName);
我需要知道如何在 const 中发送更改。只是一个简单的将文本添加到空状态。示例:状态是 apples:'',我想在其中添加 '红色美味'。
解决方案
mapDispatchToProps
为您提供了一种访问connect
组件action creators
的方法。假设您有一个增加counter
状态的动作创建者
export const change = value =>({
type: 'CHANGE_FRUIT',
fruit : value
})
并且您想value
从您的组件之一传递。首先connect
像你已经在做的那样在这个组件中使用 HOC。现在您需要incrementCounter
从您的actions
文件夹中导入
import { change as changeFruit } from './actions/fruit'
现在mapDispatchToProps
像这样使用
const mapDispatchToProps = dispatch =>({
change : fruit => dispatch(changeFruit(fruit))
})
现在您action creator
在组件内部有一个序列化props
,当您调用它时,props.increment(2)
这将等同于调用
dispatch(changeFruit('apple'))
这就是为什么您应该始终这样做props.increment
而不是直接dispatch
在组件内部调用的原因。
所以你的组件内部的完整实现可能是这样的
import { change as changeFruit } from './actions/fruit'
class Component extends React.component{
render(){
const { fruit, change } = this.props
return(
<>
<div>{fruit}</div>
<button onClick={() => change('orange')}>Change to orange</button>
</>
)
}
}
const mapStateToProps = state =>({
fruit : state.fruit
})
const mapDispatchToProps = dispatch =>({
change : fruit => dispatch(changeFruit(fruit))
})
export default connect(mapStateToProps, mapDispatchToProps)(Component)
你的减速器应该是这样的
const initialState = {
fruit: 'apple'
}
export const reducer = (state = initialState, action) =>{
switch(action.type){
case 'CHANGE_FRUIT' : return{
...state,
fruit : action.fruit
}
default : return state
}
}
推荐阅读
- python - Linux终端执行Python脚本的方式与空闲不同
- javascript - 如何让Parent DIV的Child DIV充当Parent DIV
- plugins - LibVLC v3.0.3 - 如何知道我的应用程序需要的唯一插件是什么?
- arrays - 使用 firebase 在 swift 中实现对提要帖子的评论
- php - 将 PHP/MySQL 数组编码为 JSON 的问题
- javascript - 为什么确认后我的 onclick 事件中的代码没有运行?
- java - MongoDB Java驱动程序API文档中可用的DBCursor和MongoCursor之间的区别
- mongodb - org.mongodb.scala:从返回的文档中获取值
- maven - 在线程“主”java.lang.NoClassDefFoundError 中获取异常: org/spark_project/guava/cache/CacheLoader 用于 maven 项目
- vhdl - VHDL基于布尔常数分配范围