商店更新后,useEffect不会触发

时间:2020-10-02 19:21:30

标签: javascript reactjs react-redux

我正在尝试从Api检索数据并将其保存在Redux存储中,然后在屏幕上打印。

我正在使用功能组件。

然后,当数据返回embedToken并停留在undefined时,我认为应该在存储“刷新”时对其进行更新

App.js

import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { connect } from 'react-redux'
import { requestEmbedToken } from './redux/actions'

function App(props) {
  const [embedToken, setEmbedToken] = useState(props.token);
  useEffect(() => {
    if (props.token === undefined) {
      props.requestToken();
      console.log(props.token)

      setEmbedToken(props.token)
    }
  }, [props]);
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
          Here's the token {JSON.stringify(embedToken)}
      </header>
    </div>
  );

}
const mapStateToProps = (state) => ({
  token: state.embedToken,
})

const mapDispatchToProps = (dispatch) => {
  return ({
    requestToken: () => dispatch(requestEmbedToken())
  })
}
export default connect(mapStateToProps, mapDispatchToProps)(App)

操作

import axios from 'axios';
export const saveEmbedToken = token => ({
    type: 'SAVE_EMBED_TOKEN',
    payload: {
        token
    }
})
export const requestEmbedToken = () => (dispatch) => {

    return axios.get('http://localhost:7071/api/getpbiTokens')
        .then(response => {
            console.log("token embed", response)
            dispatch(saveEmbedToken(response.data.token))
        })
}

减速器

import { combineReducers } from 'redux'

function reportingActions(state = {}, action) {
    switch (action.type) {
        case 'SAVE_EMBED_TOKEN':
            return {
                ...state,

                embedToken: action.payload.token

            }
        default: // need this for default case
            return state

    }
}
const reportingReducers = combineReducers({
    reportingActions
})
export default reportingReducers

1 个答案:

答案 0 :(得分:1)

令牌的实际路径是if (afterStatus == "Service Raised" && beforeStatus != "Service Raised") { ... send relevant message } 而不是state.reportingActions.embedToken

解决此问题

state.embedToken