【发布时间】:2019-11-18 08:06:45
【问题描述】:
//Reducer
const initialState = {
error: false,
fetching: false,
myData: []
}
export const getDataReducer = (state = initialState, action) => {
switch (action.type) {
case ActionTypes.MyData.fetch.request:
return { ...state,
fetching: true,
error: false,
myData: initialState.myData
}
case ActionTypes.MyData.fetch.success:
return {
...state,
myData: action.payload
fetching: false,
error: false
}
case ActionTypes.MyData.fetch.error:
return {
...state,
error: true,
fetching: false
}
}
export const getError = (state) => get(state, 'myData.error', false);
const mapStateToProps = (state) => {
return getMyData(state);
}
export const getMyData = createSelector(
[getClientId, getFetching, getError],
(clientId, fetching, error) => {
console.log("in selector:", fetching, error)
const state = store.getState();
const myData = getData(state);
let hasErrorOrNoData = error ? error : myData.length === 0;
hasErrorOrNoData = fetching ? false : hasErrorOrNoData;
console.log("in selector hasErrorOrNoData:", hasErrorOrNoData)
return {
error,
fetching,
hasErrorOrNoData,
myData
}
}
)
export const DataTable = ({
error,
fetching,
hasErrorOrNoData,
myData
}) => {
console.log("in component this gets called only once")
return ( <
componentX rows = {
myData
}
fetching = {
fetching
}
error = {
hasErrorOrNoData
}
errorComponent = { < NoDataMessage
isError = {
error
}
/>
}
/>
)
}
问题:最初,error 的值为 false,fetching 为 true。稍后获取为假,错误为真(因为 API 调用失败)。即使选择参数的值发生了变化,为什么渲染没有发生?我在渲染中放了一个 console.log 来检查,但只执行了一次。
仅供参考:获取和 clientId 的更改确实会触发渲染,它只是不会触发的错误。
添加reducer代码
【问题讨论】:
-
是所有代码吗?你把 DataTable 连接到 redux 了吗?
-
是的,我进行了连接,但不确定是否值得将所有代码放在这里。我相信我在选择器方法或 mapStatToProps 周围遗漏了一些东西。
-
显示你的 getError 选择器
-
添加为代码的第一行。
-
还添加了reducer
标签: javascript react-redux reselect