【发布时间】:2019-10-09 23:19:02
【问题描述】:
我的问题是 mapStateToProps 返回未定义。也许我在状态中调度或在数据来自服务器之前呈现应用程序时遇到了一些问题?我无法理解。所以应用程序在没有 redux 的情况下只需要 componentDidMount 就可以正常工作,但是我对 redux 有一些问题 所以我有一个顶级组件App:
const App = () => {
return (
<Provider store={store}>
<Screen />
</Provider>
)
}
我有 thunk meddleware 的商店:
const store = createStore(reducer, applyMiddleware(ReduxThunk));
两种类型的动作:
export const fetchData = (newPhotos) => async (dispatch) => {
function onSuccess(success) {
dispatch({
type: FETCH_DATA,
payload: success})
return success
}
function onError(error) {
dispatch({type: FETCH_FAILED, error})
}
try {
const URL = 'https://api.unsplash.com/photos/?client_id=cf49c08b444ff4cb9e4d126b7e9f7513ba1ee58de7906e4360afc1a33d1bf4c0';
const res = await fetch(URL);
const success = await res.json();
console.log(success);
return onSuccess(success);
} catch (error) {
return onError(error)
}
};
减速器:
const initialState = {
data: []
}
export default dataReducer = (state = initialState, action) => {
console.log(action);
switch (action.type) {
case FETCH_DATA:
return {
data: action.payload
}
case FETCH_FAILED:
return {
state
}
default: return state;
}
}
组合减速器:
export default combineReducers({
fetchedData: dataReducer
});
和我的渲染组件:
class HomeScreen extends Component {
render() {
console.log(this.props)
const {navigation, data} = this.props;
return (
<ScrollView>
<Header />
<ImageList navigation={navigation} data={data}/>
</ScrollView>
)
}
}
const mapStateToProps = state => {
return {
data: state.fetchedData.data
}
}
export default connect(mapStateToProps, {fetchData})(HomeScreen);
【问题讨论】:
-
state.fetchedData 是否也未定义?
标签: reactjs react-native react-redux