【问题标题】:Why Redux Strore does not add new entry为什么 Redux Store 不添加新条目
【发布时间】:2020-09-10 18:26:33
【问题描述】:

我正在关注这个tutorial。我无法再向 Redux 商店添加一个条目。 像这样修改file

const storeNavItemsData = ( data ) => ( {
type: "STORE_NAV_ITEMS",
data,
 } );

.......

export function fetchNavItemsData() { 
return function(dispatch){
   return fetchFromExternal( ).then( res => dispatch(storeNavItemsData(res)) );
   }
 }

file中添加了调用外部系统的新功能

   export function fetchFromExternal( ) {
return fetch( "http:/result.json" )
    .then( res => res.json( ) )
    .then( res => res.items );
  }

我已经像这样修改了this 文件

import { fetchData, fetchNavItemsData} from "../store";
.....
Home.serverNavFetch = fetchNavItemsData;
..... 
const mapDispatchToProps = {
fetchData,
fetchNavItemsData,
};

现在修改了这个file

  const dataRequirements =
    routes
        .filter( route => matchPath( req.url, route ) ) 
        .map( route => route.component ) 
        .filter( comp => comp.serverFetch )
        .map( comp => store.dispatch( comp.serverFetch( ) ) )
        .filter( comp1 => comp1.serverNavFetch )
        .map( comp1 => store.dispatch( comp1.serverNavFetch( ) ) ); 

在我没有看到 Redux 存储按预期填充后,值是空白的。

            window.REDUX_DATA = {"loggedIn":true,"data":[],"navItems":[]}

你能告诉我我做错了什么吗?

【问题讨论】:

  • redux 开发工具可以提供有价值的信息,例如:动作是否被调度,动作是否导致状态变化。

标签: reactjs redux react-redux react-router


【解决方案1】:

根据 repo 中的代码尝试添加一个新的 reducer 来添加新的商店实体 -

const reducer = combineReducers( {
    loggedIn: sessionReducer,
    data: dataReducer,
    navData : navReducer // new reducer added here
} );

navReducer.js // this is the reducer file
const dataReducer = ( state = [ ], action ) => {
    switch ( action.type ) {
        case "STORE_NAV_ITEMS":
            return action.data;
        default: return state;
    }
};

要访问存储在 redux 存储中的值,请将存储映射到组件文件-

const mapStateToProps = ( state ) => ( {
navData: state.navData,
});

现在,您可以将值作为道具访问 - this.props.navData

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 1970-01-01
    • 2019-05-18
    • 1970-01-01
    • 2018-08-09
    • 2020-03-23
    • 1970-01-01
    • 2020-05-04
    相关资源
    最近更新 更多