我目前有一个组件,可以从后端提取一副纸牌,并尝试从这些纸牌的值中创建图表。首次加载时,一切正常,并且将填充图表。然而,在刷新时,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 },
});
}
};
我看过类似的文章,这些文章建议我将甲板存储在localstorage中,但是我还有其他调用getDecks的组件来显示它们中的数据,与此类似,没有任何问题。有人对此有任何提示或可能的原因吗?谢谢。
尝试执行此操作,看看是否可行。调用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()。