Redux 存储在分派后不更新

BIl*_*omo 1 reactjs react-redux

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

事务.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);
Run Code Online (Sandbox Code Playgroud)

客户端.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'));
Run Code Online (Sandbox Code Playgroud)

商店.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);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

事务操作.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})
      })
  }
}
Run Code Online (Sandbox Code Playgroud)

BIl*_*omo 5

我自己发现了问题。实际上数据得到更新,只是有点晚。在检索数据之前,数据已经作为道具传递给子组件,其中子组件映射该数据为空。这就是问题的原因。所以我在 null 渲染 null 时进行验证,否则渲染数据。子组件获取数据后,会自动重新渲染以显示数据。