2016-11-21 3 views
0

Aus irgendeinem Grund wird beim Laden meiner Webanwendung der Status 'currentView' auf "Subjects" anstatt auf den Anfangswert "schools" gesetzt, obwohl keine Aktion ausgeführt wurde versandt. Warum ist das der Fall?Reduxstatus ändert sich beim Laden, obwohl keine Aktion ausgelöst wurde

actions.js

export function showSubjects(schoolId) { 
    return { 
    type: 'SHOW_SUBJECTS', 
    schoolId 
    }; 
} 

browse.js

const initialState = { 
    currentView: 'schools', 
    schools: [{id: 'AAAA', name: 'aaaa'}, {id: 'BBBB', name: 'bbbb'}], 
    subjects: [{id: 'CCC', name: 'ccc'}, {id: 'DDD', name: 'ddd'}] 
}; 

function browse(state = initialState, action) { 
    switch (action.type) { 
    case 'SHOW_SUBJECTS': 
     return { 
     ...state, 
     currentView: 'subjects' 
     }; 
    default: 
     return state; 
    } 
} 

export default browse; 

BrowseReduxContainer.jsx

import { connect } from 'react-redux'; 
import { showSubjects } from '../actions/actions'; 
import Browse from '../components/Browse.jsx'; 

function propsFilter(state) { 
    switch (state.currentView) { 
    case 'schools': 
     return state.schools; 
    case 'subjects': 
     return state.subjects; 
    default: 
     throw new Error(`No such view: ${state.currentView}`); 
    } 
} 

const mapStateToProps = (state) => ({ 
    schools: propsFilter(state) 
}); 

const mapDispatchToProps = (dispatch) => ({ 
    showSubjects: (schoolId) => { 
    dispatch(showSubjects(schoolId)); 
    } 
}); 

const BrowseReduxContainer = connect(mapStateToProps, mapDispatchToProps)(Browse); 

export default BrowseReduxContainer; 

Browse.jsx

import React from 'react'; 
import RaisedButton from 'material-ui/RaisedButton'; 

const Browse = (props) => (
    <div> 
    {props.schools.map((school) => (
     <RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} /> 
    ))} 
    </div> 
); 

export default Browse; 

Andere relevante Dateien, falls erforderlich, können hier eingesehen werden: https://github.com/Joonpark13/serif.nu/tree/feature/browse

Antwort

3

Ihre RaisedButton verursacht das Problem:

<RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} /> 

Sie führen showSubjects im onClick Handler statt eine Referenz übergeben. Stattdessen sollte es onClick={() => props.showSubjects(school.id)} sein, damit die Funktion nur nach dem Klicken ausgeführt wird.

Als Alternative können Sie auch ändern Sie Ihre mapDispatchToProps:

const mapDispatchToProps = (dispatch) => ({ 
    showSubjects: (schoolId) =>() => { 
    dispatch(showSubjects(schoolId)); 
    } 
}); 
+0

Kann nicht glauben, dass ich den Rückruf verpasst. Vielen Dank. –

Verwandte Themen