我的问题是mapStateToProps返回未定义。在数据来自服务器之前,我可能在状态分配或应用渲染方面遇到一些问题?我听不懂因此,应用程序可以在没有redux的情况下仅使用componentDidMount即可正常工作,但是我在redux上存在一些问题 所以我有一个顶级组件App:
const App = () => {
return (
<Provider store={store}>
<Screen />
</Provider>
)
}
我的商店里有笨拙的混合软件:
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);
答案 0 :(得分:0)
fetchData
操作将不会被单独调用。您需要像{p>那样显式调用(在componentDidMount
中,并且可能在componentDidUpdate
中)
class HomeScreen extends Component {
componentDidMount() {
this.props.fetchData(/* I don't know where you are going to take newPhotos argument */);
}
render() {
//...
}
}