动作完成后执行函数

IT技术 javascript reactjs redux react-redux
2021-05-06 22:57:52

嘿伙计们今天开始使用 Redux,因此正在构建一个非常基本的项目,即通过单击“增量/减量”按钮来增量/减量数字。这是它的一个小代码!请看看

动作创建器文件

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

减速器文件

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

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

1个回答

你的动作的运行流程是:

  • this.props.increment(this.props.ands)运行,在这一点上,this.props.ans0
  • this.props.in(this.props.ans)紧随其后运行并打印0在您的App.js
  • 状态改变,增量组件重新渲染
  • console.log(this.props.ands)(在render函数中)运行。

要获得所需的行为,您可以incomponentDidUpdate生命周期方法中调用回调函数

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