作为新的React开发人员尝试使用Redux。我想调度一个传递字符串的操作,该操作会将text属性更新为新状态。
这是我的方法。
const notesReducer = (state = 'Initial State', action) => {
switch(action.type) {
case "ADD_NOTE":
return({
text: action.text
})
default:
return state;
}
};
const addNoteText = (note) => {
return ({
type: "ADD_NOTE",
text: note
})
};
const store = Redux.createStore(notesReducer);
console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());
动作创建者addNoteText()接受一个参数以传递给text属性。请帮助
答案 0 :(得分:2)
这是我对这一挑战的解决方案,您真正需要改变的只有切换语句中返回的内容:
const ADD_NOTE = 'ADD_NOTE';
const notesReducer = (state = 'Initial State', action) => {
switch(action.type) {
case ADD_NOTE:
return action.text
default:
return state;
}
};
const addNoteText = (note) => {
return {
type: ADD_NOTE,
text: note
}
};
const store = Redux.createStore(notesReducer);
console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());
答案 1 :(得分:0)
const notesReducer = (state = {
text: ''
}, action) => {
switch(action.type) {
case "ADD_NOTE": {
return Object.assign({}, state, { text: action.text })
}
default:
return state;
}
};
const addNoteText = (note) => {
return(
{
type: "ADD_NOTE",
text: note
}
)
};
const store = Redux.createStore(notesReducer);
console.log(store.getState());
store.dispatch(addNoteText('Hello!'));
console.log(store.getState());