在React Native中获取API数据,特别是在reducer中使用Redux,可以按照以下步骤进行:
npm install redux react-redux
createStore
函数来创建store,并将reducer传递给它。例如:import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
fetchData
的Action:export const fetchData = () => {
return async (dispatch) => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
}
};
};
const initialState = {
data: null,
error: null,
};
const dataReducer = (state = initialState, action) => {
switch (action.type) {
case 'FETCH_DATA_SUCCESS':
return { ...state, data: action.payload, error: null };
case 'FETCH_DATA_FAILURE':
return { ...state, data: null, error: action.payload };
default:
return state;
}
};
export default dataReducer;
connect
函数将Redux store连接到React Native组件。在组件中,可以通过props访问store中的数据和触发Action。例如:import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { fetchData } from './actions';
const MyComponent = ({ data, error, fetchData }) => {
useEffect(() => {
fetchData();
}, []);
if (error) {
return <Text>Error: {error}</Text>;
}
if (!data) {
return <Text>Loading...</Text>;
}
return (
<View>
<Text>Data: {data}</Text>
</View>
);
};
const mapStateToProps = (state) => ({
data: state.data,
error: state.error,
});
export default connect(mapStateToProps, { fetchData })(MyComponent);
通过以上步骤,你可以在React Native中使用Redux来获取API数据。在reducer中处理API响应,并将数据存储在store中。然后,通过连接Redux到React Native组件,可以在组件中访问store中的数据,并在需要时触发API请求的Action。
领取专属 10元无门槛券
手把手带您无忧上云