动作完成后执行功能

时间:2019-08-02 14:36:24

标签: javascript reactjs redux react-redux

大家好,今天开始使用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
})

Increment.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?

1 个答案:

答案 0 :(得分:2)

您的操作的运行流程为:

  • #create some dummy data rows=[] rows.append(["test","testlink",1]) rows.append(["test 2","test2link",1]) rows.append(["test 3","test3link",1]) rows.append(["test","testlink",2]) rows.append(["test","testlink",1]) rows.append(["test 2","test2link",1]) rows.append(["test 3","test3link",1]) rows.append(["test ","testlink",3]) rows.append(["test 3","test3link",3]) rows.append(["test ","testlink",4]) rows.append(["test 3","test3link",4]) rows.append(["test 2","test2link",2]) #filter out duplicates newRows = [] for elem in rows: if elem not in newRows: newRows.append(elem) rows = newRows #sort the lists rows = sorted(rows,key=lambda x: (x[0],x[2])) 运行,此时,this.props.increment(this.props.ands)this.props.ans
  • 0之后立即运行,并在您的this.props.in(this.props.ans)中打印0
  • 状态已更改,增量组件已重新呈现
  • App.js(在console.log(this.props.ands)函数中)运行。

要具有所需的行为,可以在render生命周期方法内调用in回调函数。

componentDidUpdate