【发布时间】:2019-08-02 14:36:24
【问题描述】:
大家好,今天开始使用 Redux,因此正在构建一个非常基本的项目,即通过单击“递增/递减”按钮来递增/递减数字。 这是一个小代码!请看一下
动作创建者文件
export const increment=(num)=>{
return {
type:'increment',
payload:num
}
}
reducers 文件
const change=(change=0,action)=>{
if(action.type==='increment'){
return action.payload+1
}
return change
}
export default combineReducers({
change
})
增量.js
class Increment extends Component {
render() {
console.log(this.props.ans)
return (
<div>
<button onClick={()=>{this.props.increment(this.props.ans)}}>Increment</button>
</div>
)
}
}
const mapstatetoprops=(state)=>{
return {ans:state.change}
}
export default connect(mapstatetoprops,{increment}) (Increment)
现在我面临的问题是在 Increment.js 中单击按钮 Increment 执行两个函数
第一个
this.props.increment(this.props.ans)
//which calls the action creater and changes the state
第二个
this.props.in(this.props.ans)
//which is a callback to the parent component as i want to pass the value to app.js from both Increment/Decrement.js and then render it to screen
所以我的 App.js 看起来像
const App=(props)=>{
console.log(props)
return (
<div>
<Increment />
<Decrement/>
Count: {props.ans}
</div>
);
}
const mapstatetoprops=(state)=>{
console.log(state)
return {ans:state.change}
}
export default connect(mapstatetoprops) (App);
现在如果我在 App.js 中 console.log(val) 和在 Increment.js 文件中 console.log(this.props.ans)
我发现如果我的原始值为 0,那么 Increment.js 中的 this.props.ans 给了我 1,但在 App.js 中 this.val 仍然给了我 0..so 在操作更新状态之前我在 App 中接收值。 js。操作成功更新状态后,如何运行并更新 App.js?
【问题讨论】:
-
最好将您的应用程序组件与 redux 存储连接,并将单个函数传递给递增和递减组件。调用按钮的 onClick 函数,还传递一个字符串值是否是 inc 或 dec 计数器。您只需要 App.js 中的计数器值
-
@MayankShukla 在那里修改了我的解决方案,你可以检查并告诉我这是正确的方法吗?好吧,它工作正常。
标签: javascript reactjs redux react-redux