我是Redux世界的新手,我正在尝试将其与React连接。 我用以下方式构造了我的应用程序:
index.js:
const userReducer = (state={
name: "max"
}, action) => {
switch(action.type){
case "SET_NAME":
state = {
...state,
name: action.payload
};
break;
return state;
};
const myLogger= (store) =>(next)=>(action)=>{
console.log("logged action: ",action);
next(action);
};
const store = createStore(combineReducers({user: userReducer}),{}, applyMiddleware(myLogger,logger));
store.subscribe(()=>{
console.log("Store upadated", store.getState());
});
ReactDOM.render(
<BrowserRouter>
<Provider store={store}>
<App/>
</Provider>
</BrowserRouter>,
window.document.getElementById('container'));
app.js:
class App extends React.Component{
render(){
return(
<div>
<SearchBar
username = {this.props.user.name}/>
</div>
)
}
}
const mapStateToProps = (state) => {
return{
user: state.user,
math: state.math
};
};
const mapDispatchToProps = (dispatch) => {
return{
setName: (name) =>{
dispatch({
type: "SET_NAME",
payload: name
});
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
searchBar.js:
export default class SearchBar extends React.Component{
render(){
return(
<div>
Name: {this.props.username}
</div>
)
}
}
当我尝试将其传递给name
组件时,似乎无法识别来自userReducer
的{{1}}变量。
我不确定为什么吗?我是否试图通过使用SearchBar
来提供存储来构造我的index.js
错误?也许我的连接功能出问题了?
错误:
Provider
答案 0 :(得分:0)
在redux中...您从不更改状态的原始副本...您需要在执行每个操作后返回一个新副本。
在执行任何操作之前,您还需要返回一个初始值...以为您的switch default case
...在应用程序加载时进行Redux存储初始化
const userReducer = (
state = {
name: 'max',
},
action,
) => {
switch (action.type) {
case 'SET_NAME':
return {
...state,
name: action.payload,
};
default:
return state;
}
};
答案 1 :(得分:0)
我认为您的代码应该可以工作,或者您的导入错误,我所看到的唯一缺少的是括号:
switch(action.type){
case "SET_NAME":
state = {
...state,
name: action.payload
};
break;
}
return state;
}
我认为您的提供商也应该包装路由器。 但是目前,这应该不会阻塞。
您还可以使用redux开发工具(浏览器扩展)查看问题出处:
要使用它,请将以下行添加到index.js:
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(combineReducers({user: userReducer}), composeEnhancers(applyMiddleware(myLogger)));