页面刷新时删除了React + Redux状态

时间:2020-06-03 02:30:17

标签: reactjs redux react-redux use-effect

我目前有一个组件,可以从后端提取一副纸牌,并尝试从这些纸牌的值中创建图表。首次加载时,一切正常,并且将填充图表。但是,在刷新时,deck道具似乎未定义(尽管redux devtools显示它仍然存在)。

UseEffect:

useEffect(() => {
  getDecks();                      // sets "decks"
  populateData();
}, []);
  const populateData = () => {
    var data = [0, 0, 0, 0, 0];
    cardArray = decks[0].cards;                // crashes here on reload; decks is undef.

    ...
    createChart(data);
  };
export const getDecks = () => async (dispatch) => {
  try {
    const res = await axios.get("/api/decks");
    dispatch({
      type: GET_DECKS,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: DECK_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

甲板减速器的初始状态:

const initialState = {
  decks: [],
  currentCard: 0,
  loading: true,
  error: {},
  isFlipped: false,
};

我看过类似的文章,这些文章建议我将甲板存储在localstorage中,但是我还有其他调用getDecks的组件来显示它们中的数据,与此类似,没有任何问题。有人对此有任何提示或可能的原因吗?谢谢。

2 个答案:

答案 0 :(得分:0)

尝试执行此操作,看看是否可行。调用useEffect()的组件应如下所示:

import PropTypes from "prop-types";
import { connect } from "react-redux";
const deckComponent = ({decks}) => {
useEffect(() => {
  getDecks();                 
}, []);
useEffect(() => {                
  populateData();
}, [decks]);

// rest of the component goes here
 return(
.............
    );
};


deckComponent.propTypes = {
  decks: PropTypes.object.isRequired,
  getDecks: PropTypes.func.isRequired,
};
const mapStateToProps = (state) => ({
  decks: state.decks,
});

export default connect(mapStateToProps, {
  getDecks,
})(deckComponent);

它的作用是,只要加载了组件,就会调用getDecks()函数以更改后端decks状态。第二个useEffect在redux存储上监视此更改,并调用populateData()。

答案 1 :(得分:0)

发现了问题。很明显,redux存储在刷新时消失是很常见的,因此将应用程序包装在持久存储中(例如redux-persist)会自动为我解决问题。谢谢大家的建议。