派送后商店值不变

时间:2019-02-07 08:34:25

标签: reactjs redux react-redux mern

我是新来应对redux的人,我面临着商店便笺更改其值的问题。我阅读了手册,然后实施了减速器和操作。已实现ACTION AND Reducer,但状态未更新。任何帮助将不胜感激。

有关我的组件文件,请参见下文

import React from 'react'
import { Grid } from 'semantic-ui-react'
import uuid from 'uuid'
import axios from 'axios'
import _ from 'lodash'
import PropTypes from "prop-types";

import EditableTimerList from './EditableTimerList'
import ToggleableTimerForm from './ToggleableTimerForm'
import { newTimer } from './helpers'
import { updateAll, createUrlWithParams, updateTrackOnStartOrStop } from './services';
import Filters from './Filters';
import { connect } from "react-redux";
import {getDataForTimerDashBoard} from '../actions/timerAction';

var querystring = require('querystring');

class TimerDashboard extends React.Component {
  constructor () {
    super()
    this.queryJson = { runningSince: '', title: ''};

    this.state = {
      timers: [
        {
          title: 'The default one',
          description: 'This is a description',
          elapsed: null,
          runningSince: null,
          id: uuid.v4(),
          updateDate: new Date().toISOString()
        }
      ]
    }
  };
    componentDidMount() {
        this.getData(this);
        console.log(this.props.timers);
    }

  getData(that) {                   

  this.props.getDataForTimerDashBoard(this.state.timers);
  }

  updateTimer (attrs) {
  }

  createTimer (timer) {
  }

  deleteTimer (timerId) {      }

  startTimer (timerId) {
  }

  stopTimer (timerId) {
  }


  onQueryChange(query) {
  }

  saveDataToState(that, data) {
  }

  render () {
    const onQueryChange = _.debounce((query)=>{this.onQueryChange(query)}, 400);
    return (
      <div className="container">
          <div className="row">
              <EditableTimerList
                  timers={this.state.timers}
                  onFormSubmit={attrs => this.updateTimer(attrs)}
                  onTrashClick={timerId => this.deleteTimer(timerId)}
                  onStartClick={timerId => this.startTimer(timerId)}
                  onStopClick={timerId => this.stopTimer(timerId)}
              />
              <ToggleableTimerForm
                  onFormSubmit={timer => this.createTimer(timer)}
              />
              <Filters
                  onTextChange={(query)=>{onQueryChange(query)}}
                  onCheckboxChange={(query)=>{this.onQueryChange(query)}}
              />
          </div>
      </div>
    )
  }
}


TimerDashboard.propTypes = {
    getDataForTimerDashBoard: PropTypes.func.isRequired,
    auth: PropTypes.object.isRequired,
    errors: PropTypes.object.isRequired,
    timers: PropTypes.object.isRequired
};


const mapStateToProps = state => ({
    auth: state.auth,
    errors: state.errors,
    timers: state.timers
});

export default connect(
    mapStateToProps,
    {getDataForTimerDashBoard}
)(TimerDashboard);

Store.js

import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";

const initialState = {};

const middleware = [thunk];

const store = createStore(
  rootReducer,
  initialState,
  compose(
    applyMiddleware(...middleware),
    //window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
  )
);


export default store;

请参阅下面的我的类型文件

type.js

export const GET_ERRORS = "GET_ERRORS";
export const USER_LOADING = "USER_LOADING";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const LOAD_TIMER_DATA = "LOAD_TIMER_DATA";

reducer.js

import {LOAD_TIMER_DATA} from "../actions/types";
import uuid from 'uuid';
const isEmpty = require("is-empty");

const initialState = {
    isAuthenticated: false,
    user: {},
    loading: false,
    timers: {}
};

export default function (state = initialState, action) {
    switch (action.type) {
        case LOAD_TIMER_DATA:
            console.log(action)
            return {
                ...state,
                isAuthenticated: !isEmpty(action.payload.usertoken),
                user: action.payload.usertoken,
                timers: action.payload.timers
            };
        default:
            return state;
    }
}

计时

import axios from "axios";
import jwt_decode from "jwt-decode";

import {GET_ERRORS, LOAD_TIMER_DATA} from "./types";

var querystring = require('querystring');


// Register User
export const getDataForTimerDashBoard = (timerData) => async  dispatch => {
    const token = localStorage.getItem("jwtToken");
    const decoded = jwt_decode(token);

    //If no data remains in db, put the two dummy data of state into the db
    await  axios.get('/getAll').then(function (response) {
        let savedTimers = [];
        if (response.data.length === 0) {
            timerData.timers.forEach((timer) => {
                axios.post('/insert',
                    querystring.stringify(timer), {
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        }
                    }).then(function (response) {
                    timer.id = response.data.id
                    savedTimers.push(timer);
                    dispatch({
                        type: LOAD_TIMER_DATA,
                        payload: savedTimers
                    })
                }).catch(err => {
                    dispatch({
                        type: GET_ERRORS,
                        payload: err.response.data
                    })
                });
            });
        } else {
            alert(response.data);
            const payload ={};
            payload.timers = response.data;
            payload.usertoken = decoded;
            dispatch({
                type: LOAD_TIMER_DATA,
                payload: payload,
            })
        }
    });
};

1 个答案:

答案 0 :(得分:0)

我认为代码中存在问题,而在有效负载中调度时,您仅推动SavedTimers,而在减速器中,您试图访问 userToken

savedTimers.push(timer);
    dispatch({
    type: LOAD_TIMER_DATA,
    payload: savedTimers
})

也请将userToken添加到您的有效负载

编辑

import axios from "axios";
import jwt_decode from "jwt-decode";

import {GET_ERRORS, LOAD_TIMER_DATA} from "./types";

var querystring = require('querystring');    

// Register User
export const getDataForTimerDashBoard = (timerData) => async  dispatch => {
    const token = localStorage.getItem("jwtToken");
    const decoded = jwt_decode(token);
    const payload ={};
    payload.usertoken = decoded;

    //If no data remains in db, put the two dummy data of state into the db
    await  axios.get('/getAll').then(function (response) {
        let savedTimers = [];
        if (response.data.length === 0) {
            timerData.timers.forEach((timer) => {
                axios.post('/insert',
                    querystring.stringify(timer), {
                        headers: {
                            "Content-Type": "application/x-www-form-urlencoded"
                        }
                    }).then(function (response) {
                    timer.id = response.data.id
                    savedTimers.push(timer);
payload.timers = savedTimers;
            dispatch({
                type: LOAD_TIMER_DATA,
                payload: payload,
            })

                }).catch(err => {
                    dispatch({
                        type: GET_ERRORS,
                        payload: err.response.data
                    })
                });
            });
        } else {
            payload.timers = response.data;
            dispatch({
                type: LOAD_TIMER_DATA,
                payload: payload,
            })
        }
    });
};
相关问题