如何解决我的 react redux 应用程序有什么问题,因为它没有按预期呈现?
我开始使用 redux 只是为了测试一下我开始使用 combineReducers 来设计更结构化的方法,但它的工作原理与每个人建议的不一样。我一直在挠头,我的问题出了什么问题方法,因为我遵循了他们官方网站上的每一个要点。
index.js
import React from 'react';
import {createStore} from 'redux';
import {Provider} from 'react-redux';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reducer from './reducer';
import Welcome from './Components/Welcome';
const store=createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
<Welcome/>
</Provider>,document.getElementById('root')
);
Welcome.js 文件
import React from 'react'
import {connect} from 'react-redux';
import {FIRST} from '../Actions';
function Welcome({count,dispatch}) {
dispatch({type:FIRST});
return (
<div>
<h1> Wow it's great {count}</h1>
</div>
)
}
const mapStateToProps=(store) =>({
count:store.count
})
export default connect(mapStateToProps)(Welcome);
loginsearch.js
import {FIRST} from './Actions';
const initialstore={
count:1,total:1
}
function loginreducer(state=initialstore,action)
{
if(action.type === FIRST)
{
return{...state,count:0};
}
return state;
}
export default loginreducer;
searchreducer.js
const initialstore={
item:1,search:1
}
function searchreducer(state=initialstore,action)
{
return state;
}
export default searchreducer;
reducer.js
import {combineReducers} from 'redux';
import loginreducer from './loginreducer';
import searchreducer from './searchreducer';
export default combineReducers({
loginreducer,searchreducer
})
当我在 Welcome.js 中 console.log(count)
之后 dispatch({type:FIRST})
我得到未定义,但是在应用程序中我应该得到哇,太棒了 0
解决方法
问题是,您组合了减速器,但是当从 mapStateToProps 调用状态时,您忘记添加您实际引用的减速器,因此您未定义。
我为你的减速器添加了键,所以在外面打电话会容易得多。并更新了 mapStateToProps
这是解决您的问题的示例,
/*reducer.js*/
import {combineReducers} from 'redux';
import loginreducer from './loginreducer';
import searchreducer from './searchreducer';
export default combineReducers({
lr: loginreducer,// <== Check this line
sr: searchreducer // <== Check this line
})
/*welcome.js*/
const mapStateToProps=(store) =>({
count:store.lr.count,// <== Check this line
})
export default connect(mapStateToProps)(Welcome);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。