简体   繁体   English

存储重新水化后无法使用 redux-persist 获取持久状态的值

[英]Unable to get value of persisted state using redux-persist after the store is rehydrated

So let's say I have a Home Component which it just perform api call to fetch all homeworks from the server:因此,假设我有一个 Home 组件,它只是执行 api 调用以从服务器获取所有作业:

import React, { Component } from 'react';
import { fetchHomeWorks } from '../actions';
import HomeWorkRow from '../component/HomeWorkRow';


class Home extends Component {

    componentDidMount() {
        this.props.fetchHomeWorks()
    }

    renderHomeWorks() {
        const { home_works, error, loading } = this.props;

        if(!error) {
            if(!loading){
                if(home_works.length >=1) {
                    return home_works.map(home_work => {
                        return <HomeworkRow key={uuid()} home_work={home_work} />
                    })
                }
                else
                    return <p className="pt-card col-xs-12 col-xs-offset-1 content"> No Task Yet :)</p> 
            }
            else 
                return <p>Loading...</p>
        }
    }

    render() {
        return (
            <Layout>
                { this.props.renderHomeworks() }
            </Layout>
        );
    }
}

const mapStateToProps = ({ home_work, persist }) => {
    return {
        home_works: home_work.home_works,
        persist: 
    };
};
export default connect(mapStateToProps, { fetchHomeWorks })(Home);

on page refresh, Of course it will perform the api call because of componentDidMount() lifecycle.. Now, I want to change it and use the persisted data using redux-persist so it will avoid the api call whenever page is refreshed...在页面刷新,当然它会执行,因为componentDidMount的API调用()的生命周期。现在,我想改变它,并使用persisted使用数据redux-persist这样就避免了API调用,每当页面被刷新......

I am using the redux-persist library.. Here is my app component with redux persist():我正在使用redux-persist库。这是我的带有 redux persist() 的应用程序组件:

import React, { Component } from 'react';
import { Provider } from 'react-redux';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom';
import { compose, createStore, applyMiddleware } from 'redux';
import {persistStore, autoRehydrate} from 'redux-persist';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import rootReducer from './reducers/';


class App extends Component {
  render() {
    const store = createStore(rootReducer, {}, compose(applyMiddleware(thunk, logger), autoRehydrate()));
    persistStore(store);
    return (
      <Provider store={store}>
        <Router>
          <div>
            <Route exact path="/" component={LoginForm} />
           // ... some routes which doesnt matter
          </div>
        </Router>
      </Provider>
    );
  }
}

export default App;

I know the resux persist is working because of the redux logger我知道由于 redux 记录器,resux persist 正在工作redux 记录器的快照

Now, how do I get the value of the persisted state?现在,我如何获得持久状态的值? I tried making another reducer: persistReducer import { PERSIST } from '../actions/types';我尝试制作另一个减速器: persistReducer import { PERSIST } from '../actions/types';

export default (state = [], action) => {
    switch(action.type) {
        case PERSIST:
            return { ...state, persistState: action.payload }
        default:
            return state;   
    }
};

and adding it in rootReducer :并将其添加到rootReducer

import { reducer as formReducer } from 'redux-form'

import { combineReducers } from 'redux';
import homeWorkReducer from './userReducer';
import persistReducer from './persistReducer';

export default combineReducers({
    home_works: homeWorkReducer,
    form: formReducer,
    persist: persistReducer
});

and in my Home component, i access it using在我的Home组件中,我使用

componentWillReceiveProps(nextProps) {

    if(nextProps.persist.persistState) {
        console.log(nextProps.persist.persistState.home_works.home_works)   
    }
}

and getting the values correctly:并正确获取值: 在此处输入图片说明

so how to do it correctly?那么如何正确地做到这一点呢?

Side note , but you can clean up the code a bit if you reverse the logic in your if statements:旁注,但如果您反转 if 语句中的逻辑,您可以稍微清理一下代码:

this:这个:

renderHomeWorks() {
    const { home_works, error, loading } = this.props;

    if(!error) {
        if(!loading){
            if(home_works.length >=1) {
                return home_works.map(home_work => {
                    return <HomeworkRow key={uuid()} home_work={home_work} />
                })
            }
            else
                return <p className="pt-card col-xs-12 col-xs-offset-1 content"> No Task Yet :)</p> 
        }
        else 
            return <p>Loading...</p>
    }
}

can become:可以变成:

renderHomeWorks() {
    const { home_works, error, loading } = this.props;

    if (error) return <p>Loading...</p>

    if (loading || !home_works) return <p className="pt-card col-xs-12 col-xs-offset-1 content"> No Task Yet :)</p> 

    return home_works.map(home_work => <HomeworkRow key={uuid()} home_work={home_work} />)
}
  1. You can omit the { and } for if statements that only have one expression.对于只有一个表达式的 if 语句,您可以省略{}
  2. 0 is a falsy value, so home_works.length === 0 and !home_works both return true 0是一个假值,所以home_works.length === 0!home_works都返回真
  3. You can use implicit return with fat arrow => syntax if the function only returns one expression (in almost all cases)如果函数只返回一个表达式(几乎在所有情况下),您可以使用带有粗箭头=>语法的隐式返回

For example, home_works.map(() => something()) is the same as home_works.map(() => { return something() }) .例如, home_works.map(() => something())home_works.map(() => { return something() }) You can use JSX this way also if it only returns one JSX element (such as a div, or one component).如果 JSX 只返回一个 JSX 元素(例如一个 div 或一个组件),您也可以以这种方式使用 JSX。

This code I just showed you works because as React is rendering HomeWorks, it first checks if there is an error -- if so, returns from the render function -- then, it checks if it is loading or if home_works is falsy -- if so, returns from the function -- and finally, it goes ahead and renders the list of homework rows.我刚刚向您展示的这段代码有效,因为当 React 渲染 HomeWorks 时,它首先检查是否有错误——如果有,则从渲染函数返回——然后,它检查它是否正在加载或home_works是否为假——如果所以,从函数返回——最后,它继续并呈现作业行列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM