在反应本机状态中,
是常用的,如果我们要使用数据来在手机中进行操作或显示,反应本机当然很重要,但是redux可以解决这一难题,我还是新手反应本地人,只是了解如何不使用redux以“旧”方式获取API,而是如何?在reducer中,我试图在组件中调用函数和回调,但是没有用,这是代码:
peopleReducer.js:
import { ADD_FRIENDS } from "../types";
import { INIT_PEOPLE } from "../states";
const peopleReducers = (state = INIT_PEOPLE, action) => {
switch (action.type) {
// // save image
case ADD_FRIENDS:
// find how to fetch API in react native redux
makeRemoteRequest = () => {
const { page, seed } = state;
const url = `https://randomuser.me/api/?seed=${seed}&page=${page}&results=20`;
setState({ loading: true });
fetch(url)
.then(res => res.json())
.then(res => {
setState({
data: page === 1 ? res.results : [...state.data, ...res.results],
error: res.error || null,
loading: false,
refreshing: false
});
console.warn(res.results);
})
.catch(error => {
setState({ error, loading: false });
});
};
default:
return state;
}
};
export default peopleReducers;
friends.js
import React from "react";
import { View, Text, FlatList, ActivityIndicator } from "react-native";
import { ListItem, SearchBar } from "react-native-elements";
// connect to redux
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
// import actions
import { addFriends } from "../config/redux/actions/peopleActions";
class friends extends React.Component {
componentDidMount() {
this.props.addFriends();
// this.makeRemoteRequest();
}
render() {
// console.warn(this.props.peopleListDashboard.data)
return (
<View>
<FlatList
data={this.props.peopleListDashboard.data}
renderItem={({ item }) => (
<ListItem leftAvatar={{ uri: item.picture.thumbnail }} />
)}
keyExtractor={item => item.email}
/>
</View>
);
}
}
// make accesible publicDashboard properties from reducer
const mapStateToProps = state => {
const { peopleListDashboard } = state;
return { peopleListDashboard };
};
const mapDispatchToProps = dispatch =>
bindActionCreators(
{
addFriends
},
dispatch
);
export default connect(
mapStateToProps,
mapDispatchToProps
)(friends);
关于触发器,是的,我正在使用动作 peopleAction.js
import { ADD_FRIENDS } from "../types";
export const addFriends = friendsIndex => ({
type: ADD_FRIENDS,
payload: friendsIndex
});
希望你们能给我一些线索,建议,甚至答案对我来说都是个好方法。谢谢
答案 0 :(得分:0)
我认为您需要在操作文件中而不是在reducer中获取数据,然后将响应分发到reducer上并保存在商店中。通过这种方法,您可以随时调用操作,并且此操作必须对您有用。我建议您也检查这些链接:
https://redux.js.org/introduction/getting-started
https://stackoverflow.com/questions/43848257/where-to-put-business-logic-in-redux-action-or-store
此链接可能会对您有所帮助。