简体   繁体   中英

Very Strange thing in dispatch function in react-redux

my mapstatetoprop function use state "store" and the page render. but when I dispatch to reducer directly and override current state and return nothing "undefined" the page still rendering like i did not change the state "become undefined". But here is the intersting thing I added console,log(state) to mapstatetoprop(state) and it reall prints undefined but after page alread mounted(1st case).

so i try to add setTimeout to dispatch function(2nd case) or attatch it to event page stop working(3rd case)

const mapStateToProps = (state)=>{
    console.log("mystate : ", state);
    return {searchField :state.searchField }
}

const mapDispatchToProps =(dispatch)=>{
    dispatch({type : "test"});
 --> " (1st case) console print state : undefined after didmount function run"

//commented   setTimeout(()=>{dispatch({type : "test"});},3000); 
--> "page gets error after 3 sec(2nd case)"

    return {
             onchange : (event)=> dispatch(setSearchField(event.target.value))
//commented       ,  test : ()=> {dispatch({type : "test"}); console.log("test");}
 -->" (3rd case) page gets error aftet trigger its event"
           }

}

myreducer function

const intialState = {
    searchField : '' 

}

export const searchRobots = (state = intialState , action={})=>{

    switch(action.type){
        case "CHANGE_SEARCH_FIELD" :
            return Object.assign({} , state ,{searchField : action.payload}  );

        case "test":
            break;

        default :

             return state ;

    }
}

you can't call dispatch inside mapDispatchToProps. You have to return only functions after calling of which you can call dispatch function or you can use bindActionCreators for avoiding unexpected behavior. It's only one correct way for predictable working of redux. Just never call dispatch inside mapDispatchToProps

Dont dispatch directly inside mapDispatchToProps , you do some thing like this:

const mapDispatchToProps = (dispatch) => ({
    fetchUserDetails : () => dispatch(yourAction(value))
});

Now fetchUserDetails will be available inside props as a function, so you can destructure it from the this.props and you use it anywhere you want, like:

const { fetchUserDetails } = this.props;
fetchUserDetails();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM