0

我开始使用 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')
);

欢迎.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);

登录搜索.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;

减速器.js

import {combineReducers} from 'redux';
import  loginreducer from './loginreducer';
import searchreducer from './searchreducer';

export default combineReducers({
loginreducer,
searchreducer
})

当我console.log(count)在 Welcome.js 之后dispatch({type:FIRST})

我得到未定义,但是在应用程序中我应该得到哇,这很棒 0

应用程序的图像

4

1 回答 1

1

问题是,你组合了减速器,但是当从 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);
于 2020-12-21T08:20:36.363 回答