我正在使用一个具有本机登录功能的React Native应用程序,该动作创建程序和reducer可以正常工作,但是我正在使用的求职API的动作创建者和reducer无法正常工作
这些是动作创建者:
let obj = [
{ name: "Qwerty1", status: "Development" },
{ name: "Qwerty2", status: "Development" },
{ name: "Qwerty3", status: "Staging" },
{ name: "Qwerty4", status: "Production" },
{ name: "Qwerty5", status: "Production" }
]
let order = [...new Set(obj.map(e => e.status))];
function getList(status) {
const output = obj.filter(e => order.indexOf(status) >= order.indexOf(e.status));
return output;
}
console.log(getList("Staging"));
这是import axios from "axios";
// import { Location } from "expo";
import qs from "qs";
import { FETCH_JOBS, LIKE_JOB } from "./types";
import locationify from "../tools/locationify";
const JOB_ROOT_URL = "https://authenticjobs.com/api/?";
const JOB_QUERY_PARAMS = {
api_key: "<api_key>",
method: "aj.jobs.search",
perpage: "10",
format: "json",
keywords: "javascript"
};
const buildJobsUrl = () => {
const query = qs.stringify({ ...JOB_QUERY_PARAMS });
return `${JOB_ROOT_URL}${query}`;
};
export const fetchJobs = (
region,
distance = 10,
callback
) => async dispatch => {
try {
const url = buildJobsUrl();
let job_list = await axios.get(url);
job_list = locationify(
region,
console.log(job_list.data.listings.listing),
job_list.data.listings.listing,
distance,
(obj, coords) => {
obj.company.location = { ...obj.company.location, coords };
return obj;
}
);
dispatch({ type: FETCH_JOBS, payload: job_list });
callback();
} catch (e) {
console.log("fetchJobs Action Error:", e.message);
}
};
export const likeJob = job => {
return {
payload: job,
type: LIKE_JOB
};
};
:
jobs_reducer.js
这是import { FETCH_JOBS } from "../actions/types";
const INITIAL_STATE = {
listings: []
};
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_JOBS:
return action.payload;
default:
return state;
}
}
:
likes_reducer.js
我昨天整晚都在调试它,我所知道的是我正在控制台将数据记录到我的终端上,我可以看到作业API数据的详细信息只是填充了我的终端,但是错误消息是reducers正在返回未定义。
如何返回数据并同时返回未定义?
我正在使用异步操作创建者。我在React Native应用程序上需要import _ from "lodash";
import { LIKE_JOB } from "../actions/types";
export default function(state = [], action) {
switch (action.type) {
case LIKE_JOB:
return _.uniqBy([action.payload, ...state], "id");
default:
return state;
}
}
吗?我是否正在使用具有错误的React Native版本?我知道Redux应该如何工作,所以我很困惑。
在redux-thunk
中:
reducers/index.js
我开始得到该错误的地方或该错误所引用的是import { combineReducers } from "redux";
import auth from "./auth_reducer";
import jobs from "./jobs_reducer";
import likedJobs from "./likes_reducer";
export default combineReducers({
auth,
jobs,
likedJobs
});
,如this.props.data.map()
:
components/Swipe.js
在上面,我得到import React, { Component } from "react";
import {
View,
Animated,
PanResponder,
Dimensions,
LayoutAnimation,
UIManager
} from "react-native";
const SCREEN_WIDTH = Dimensions.get("window").width;
const SWIPE_THRESHOLD = 0.25 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;
class Swipe extends Component {
static defaultProps = {
onSwipeRight: () => {},
onSwipeLeft: () => {},
keyProp: "id"
};
constructor(props) {
super(props);
const position = new Animated.ValueXY();
const panResponder = PanResponder.create({
onStartShouldSetPanResponder: (event, gestureState) => true,
onPanResponderMove: (event, gestureState) => {
position.setValue({ x: gestureState.dx, y: gestureState.dy });
},
onPanResponderRelease: (event, gestureState) => {
if (gestureState.dx > SWIPE_THRESHOLD) {
this.forceSwipe("right");
} else if (gestureState.dx < -SWIPE_THRESHOLD) {
this.forceSwipe("left");
} else {
this.resetPosition();
}
}
});
this.state = { panResponder, position, index: 0 };
}
componentWillReceiveProps(nextProps) {
if (nextProps.data !== this.props.data) {
this.setState({ index: 0 });
}
}
componentWillUpdate() {
UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);
LayoutAnimation.spring();
}
forceSwipe(direction) {
const x = direction === "right" ? SCREEN_WIDTH : -SCREEN_WIDTH;
Animated.timing(this.state.position, {
toValue: { x, y: 0 },
duration: SWIPE_OUT_DURATION
}).start(() => this.onSwipeComplete(direction));
}
onSwipeComplete(direction) {
const { onSwipeLeft, onSwipeRight, data } = this.props;
const item = data[this.state.index];
direction === "right" ? onSwipeRight(item) : onSwipeLeft(item);
this.state.position.setValue({ x: 0, y: 0 });
this.setState({ index: this.state.index + 1 });
}
resetPosition() {
Animated.spring(this.state.position, {
toValue: { x: 0, y: 0 }
}).start();
}
getCardStyle() {
const { position } = this.state;
const rotate = position.x.interpolate({
inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
outputRange: ["-120deg", "0deg", "120deg"]
});
return {
...position.getLayout(),
transform: [{ rotate }]
};
}
renderCards() {
if (this.state.index >= this.props.data.length) {
return this.props.renderNoMoreCards();
}
return this.props.data
.map((item, i) => {
if (i < this.state.index) {
return null;
}
if (i === this.state.index) {
return (
<Animated.View
key={item[this.props.id]}
style={[this.getCardStyle(), styles.cardStyle]}
{...this.state.panResponder.panHandlers}
>
{this.props.renderCard(item)}
</Animated.View>
);
}
return (
<Animated.View
key={item[this.props.id]}
style={[styles.cardStyle, { top: 10 * (i - this.state.index) }]}
>
{this.props.renderCard(item)}
</Animated.View>
);
})
.reverse();
}
render() {
return <View>{this.renderCards()}</View>;
}
}
const styles = {
cardStyle: {
position: "absolute",
width: SCREEN_WIDTH
}
};
export default Swipe;
不确定或不是函数。
我在this.props.data.map()
中遇到了同样的问题:
ReviewScreen.js
上面与import React, { Component } from "react";
import { View, Text, Button, ScrollView } from "react-native";
import { connect } from "react-redux";
class ReviewScreen extends Component {
static navigationOptions = ({ navigation }) => ({
headerTitle: "Review Jobs",
headerRight: (
<Button
title="Settings"
onPress={() => {
navigation.navigate("settings");
}}
/>
)
});
renderLikedJobs() {
return this.props.likedJobs.map(job => {
return (
<Card>
<View style={{ height: 200 }}>
<View style={styles.detailWrapper}>
<Text style={styles.italics}>{job.company}</Text>
<Text style={styles.italics}>{job.post_date}</Text>
</View>
</View>
</Card>
);
});
}
render() {
return <ScrollView>{this.renderLikedJobs()}</ScrollView>;
}
}
const styles = {
detailWrapper: {
marginBottom: 10,
flexDirection: "row",
justifyContent: "space-around"
}
};
function mapStateToProps(state) {
return { jobs: state.jobs };
}
export default connect(mapStateToProps)(ReviewScreen);
答案 0 :(得分:0)
在动作创建者中,无需调用API,而是对API数据进行Hardcore并返回。如果您的reducer始终返回未定义的错误,则错误在您的代码中。
对于异步调用,您需要使用redux-thunk或redux-saga,我建议您使用redux-saga,因为它避免了回调地狱。
答案 1 :(得分:0)
我最终像这样重构我的工作减少者:
export default function(state = INITIAL_STATE, action) {
switch (action.type) {
case FETCH_JOBS:
const { listings } = action.payload;
return { ...state, listing: listings.listing };
default:
return state;
}
}