调度后Redux商店不会更新

时间:2017-07-30 16:19:05

标签: reactjs react-redux

我正在尝试在渲染之前获取组件加载数据,因此我使用componentWillMount来调度我的getTransaction()操作以及由此产生的成功(我将redux-logger作为中间件来了解成功或失败)。 问题是我的redux商店没有得到更新。我需要将这些数据作为道具传递给子组件。 主要问题是 Transaction.js 这是我的代码

Transaction.js

import React from "react";
import { connect } from "react-redux"
import { withRouter } from 'react-router-dom';

import { getAuthenticatedUsername } from '../../utils/authorization'
import Layout from "./../layout/Index"
import Table from "../../components/table/Table"

import { getTransaction } from "../../actions/transactionActions"

import "./styles.scss"

function mapStateToProps(state){
  return {
    transaction: state.transaction
  }
}
class Transaction extends React.Component {

  componentWillMount() {
    this.props.dispatch(getTransaction());
  }

  render() {
    console.log(this.props);//transaction not get updated, only get initial state from transactionActions
    return (
      <Layout username={getAuthenticatedUsername()}>
          <Table data={this.props.transaction}/>
      </Layout>
    );
  }
}

export default connect(mapStateToProps)(Transaction);

client.js

import React from "react"
import ReactDOM from "react-dom"
import { Provider } from "react-redux"
import { 
  HashRouter,
  Link,
  Route,
  Redirect
} from 'react-router-dom'

import { isAuthenticated, setAuthorizationToken } from './utils/authorization'

import store from "./store/store"
import Login from "./pages/Login"
import Register from "./pages/Register"
import CatExpense from "./pages/isi/CatExpense"
import CatIncome from "./pages/isi/CatIncome"
import Transaction from "./pages/isi/Transaction"

import "../styles/styles.scss"

setAuthorizationToken(localStorage.jwtToken);

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    isAuthenticated() ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

ReactDOM.render(
  <Provider store={store}>
    <HashRouter>
      <switch>
        <Route exact path="/" component={Login}/>
        <Route path="/login" component={Login}/>
        <Route path="/register" component={Register}/>
        <PrivateRoute path="/transaction" component={Transaction}/>
        <PrivateRoute path="/catincome" component={CatIncome}/>
        <PrivateRoute path="/catexpense" component={CatExpense}/>
        <Redirect path="*" to="/"/>
      </switch>
    </HashRouter>
  </Provider>, document.getElementById('app'));

store.js

import { applyMiddleware, createStore } from "redux";
import axios from "axios";
import { createLogger } from "redux-logger";
import thunk from "redux-thunk";
import promise from "redux-promise-middleware";

import reducer from "../reducers/index";

const middleware = applyMiddleware(promise(), thunk, createLogger());
export default createStore(reducer, middleware);

transactionReducer.js

const initialState = {
  isFetching: false,
  isSuccess: false,
  transaction: {}
}
export default function reducer(state = initialState, action ) {
  switch (action.type) {
    case "GET_TRANSACTION_PENDING": {
      return { ...state, isFetching: true }
      break;
    }
    case "GET_TRANSACTION_REJECTED": {
      return { ...state, isFetching: false, error: action.payload }
      break;
    }
    case "GET_TRANSACTION_FULFILLED": {
      return { ...state, isSuccess: true, transaction: action.payload }
      break;
    }
  }
  return state;
}

transactionActions.js

import axios from "axios"
import jwt from "jsonwebtoken"
import { isAuthenticated } from '../utils/authorization'

export function getTransaction(){
  isAuthenticated();
  return function(dispatch) {
    axios.get("http://localhost:8000/listTransaction")
      .then((response) => {
        dispatch({type: "GET_TRANSACTION_FULFILLED", payload: response.data})
      })
      .catch((err) => {
        dispatch({type: "GET_TRANSACTION_REJECTED", payload: err})
      })
  }
}

2 个答案:

答案 0 :(得分:0)

两件事。首先,您应根据React文档在componentDidMount中发送操作。 https://facebook.github.io/react/docs/react-component.html#componentdidmount

其次,您需要将Redux的mapDispatchToProps()函数传递给connect,并传递实际操作。

  const mapDispatchToProps = (dispatch) => {
   return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
   }
  }

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)

What is mapDispatchToProps?

https://github.com/reactjs/react-redux/blob/master/docs/api.md

答案 1 :(得分:0)

我自己发现了这个问题。 实际上数据已经更新,只是迟到了。在检索数据之前,数据已作为props传递给子组件,其中子组件映射该数据为null。这就是导致问题的原因。 所以我把验证如果null渲染为null,否则渲染数据。 子组件获取数据后,它将自动重新呈现以显示数据。