gpt4 book ai didi

javascript - 在 action 完成工作后执行函数

转载 作者:行者123 更新时间:2023-11-29 20:33:41 25 4
gpt4 key购买 nike

大家好,今天开始使用 Redux,所以正在构建一个非常基本的项目,通过单击“递增/递减”按钮来递增/递减数字。这是一个小代码!请看一下

Action 创建文件

export const increment=(num)=>{
return {
type:'increment',
payload:num
}
}

reducer 文件

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 中单击“增量”按钮会执行两个函数

第一个

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);

现在如果我 console.log(val) 在 App.js 和 console.log(this.props.ans) 在 Increment.js 文件我发现如果我的原始值为 0 那么 Increment.js 中的 this.props.ans 给我 1 但在 App.js 中 this.val 仍然给我 0.. 所以在操作更新状态之前我在 App 中接收值。 js。在操作成功更新状态后,如何运行并更新 App.js?

最佳答案

你的 Action 的运行流程是:

  • this.props.increment(this.props.ands)运行,此时this.props.ans0
  • this.props.in(this.props.ans) 之后立即运行并在 App.js 中打印 0
  • 状态改变,增量组件重新渲染
  • console.log(this.props.ands)(在 render 函数中)运行。

要获得您想要的行为,您可以在 componentDidUpdate 生命周期方法中调用您的 in 回调函数。

componentDidUpdate(prevProps) {
this.props.in(this.props.ans);
}

关于javascript - 在 action 完成工作后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57328635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com