使用redux

时间:2018-07-08 12:03:25

标签: reactjs redux react-redux

我是新来的反应者,我想自己学习反应和还原。 我的应用程序中有一个类似的计数器。预期的行为是在刷新页面后保留喜欢的次数。我确实实现了代码,并且可以正常工作。但是,刷新页面时,计数器将重置为零。我尝试为补丁请求创建操作,但始终给我× TypeError: Cannot read property 'params' of undefined。谁能告诉我我的代码出了什么问题?

我的一个项目的架构看起来像这样,其中点赞是该项目的属性。

{
id: 1,
title: "A new cake recipe",
body: "Made of chocolate",
likes: 0,
created_at: "2018-07-06T14:48:23.377Z",
updated_at: "2018-07-06T14:49:59.582Z"
}

这是我的点赞内容

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Likes extends Component {

    constructor(props) {

        super(props);
        this.state = {
            likes: 0,
            updated: false
        }
        this.updateLikes = this.updateLikes.bind(this);
    }

    updateLikes() {
        this.setState((prevState) => {

            return {
                likes: prevState.likes + 1,
                updated: true
                }
            })
            
    }

    render() {

        return (
            <div>
                <button 
                    className="btn btn-success" 
                    onClick={this.updateLikes}>
                    Like <strong>{this.state.likes}</strong>
                </button> 
            </div>
        );
    }
}

function mapStateToProps(state){
    return {
        likes: state.likes
    }
}
export default connect(mapStateToProps)(Likes)

这是我的减速器

const initialState ={
    likes: 0
}
export default function(state = initialState, action) {
    console.log(action.type)
    switch(action.type){
        case 'INC_LIKES':
            return {likes: state.likes + 1}
        default:
            return state;
    }
        
}

2 个答案:

答案 0 :(得分:0)

考虑将localStorage中间件用于Redux:

  1. https://www.npmjs.com/package/redux-storage

  2. https://www.npmjs.com/package/redux-localstorage-simple

本地存储是在客户端保留应用程序状态的html 5标准方法:

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

答案 1 :(得分:0)

可以手动使用

window.localStorage在页面加载之间保持state

否则,像redux-localstorage这样的中间件库可能是合适的。

实施前者可能类似于以下内容:

操作

const updateLikes = (likes = 0) => {
  localStorage.setItem('likes', likes)
  return {type: 'INC_LIKES', payload: likes}
}

减速器

const reducer = (state = {likes: parseInt(localStorage.getItem('likes') || 0)}, action) => {
  switch(action.type) {
    case 'INC_LIKES':
      return {likes: action.payload}
    default:
      return state
  }       
}

连接

connect(mapStateToProps, {updateLikes})

用法

this.props.updateLikes(this.props.likes + 1)