componentDidMount(){
var self = this;
//selt.props is undefined too from this point !!!! WHY
// this.props.addTodo();
window.onscroll = function(){
//self.setState({ type:'ADD_TODO' });
// debugger
self.props.addTodo('param')
}
}
function mapStateToProps (state) {
return {
todos: state
};
}
function mapDispatchToProps (dispatch, ownProps) {
return {
addTodo: function(text){
dispatch({type: 'ADD_TODO', text: text, id: ++_idSeq});
}
}
}
self.props.addTodo is not a function
self.setState({ type:'ADD_TODO' }); dont init reducer ! Why ?
reducer 代码:
function todoReducer (currentState, action) {
currentState = currentState || {}; // Initial State
// debugger
console.log('reducer!');
switch (action.type) {
case 'ADD_TODO':
debugger
let newTodo = {id:1};
return Object.assign({}, currentState, newTodo);
default:
return currentState; // TODO: Always return the state
}
}
// Create Store
var todoStore = createStore(todoReducer);
let unsubscribe = todoStore.subscribe(() => console.log(todoStore.getState()))
window.store = todoStore;
var TodoListContainer = connect(mapStateToProps, mapDispatchToProps)(TodoList);
最佳答案
您需要从您的组件
进行分派(dispatch)和操作,并在reducer
中更改您的状态。
简单的例子:
组件:
componentWillMount() {
store.dispatch({ type: 'YOUR-ACTION', payload: 'yourValue' })
}
reducer :
function app(state = initialState, action) {
switch (action.type) {
case 'YOUR-ACTION':
// change your state here
default:
return state
}
}
注意事项:
从你的组件 IMO 直接发送操作对于现实世界的应用程序来说并不是真正的最佳选择,因为你耦合了你的组件。请考虑改用 containers
并更多地解耦您的应用程序。 An interesting article .
关于javascript - init 如何从 componentDidMount 更改 redux 状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44452873/