我正在使用react-native构建应用程序,遵循redux概念,现在我遇到了问题,我的组件在调度操作后没有按照它们应该更新。
稍微解释一下情节,我有一个React Class" QuestionScreen"并且我想在页面打开后立即调用API,但是当API正在执行其工作时应该呈现加载器,当它完成时,应该出现问题。这里是我的代码
PS:我是新的反应原生和超新概念,所以对解释有点帮助QuestionScreen.js
function mapStateToProps(state) {
return {
session: state.questionsReducer.session
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Actions, dispatch);
}
class QuestionsScreen extends Component {
static navigationOptions = ({navigation}) => ({
title: `${navigation.state.params.title}`,
headerRight: <Button transparent><EntypoIcon name="dots-three-vertical"/></Button>,
headerTintColor: '#0b3484',
});
constructor(props) {
super(props);
this.state = {
params: this.props.navigation.state.params.passProps
};
this.fetchSessionQuestions = this.fetchSessionQuestions.bind(this);
}
fetchSessionQuestions() {
this.props.fetchPracticeQuesions({
URL: BASE_URL + '/api/dashboard/get_chapter_question/',
chapter: this.state.params.chapter_name
});
}
componentDidMount() {
this.fetchSessionQuestions();
}
render() {
const {navigate} = this.props.navigation;
if (this.props.session.isLoading) {
return (
// Loader here
);
}
else {
const questions = this.props.session.questions;
return (
// Some questions logic here
);
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(QuestionsScreen);
questionsReducer.js
import * as types from '../actions/actionTypes';
const initialState = {
session: {
isLoading: true,
currentQuestion: 0,
questions: [],
score: 0,
timeTaken: 0,
attempted: 0
}
};
const newState = JSON.parse(JSON.stringify(initialState));
export default function questionsReducer(state = initialState, action) {
switch (action.type) {
case types.NEXT_QUESTION:
newState.session.currentQuestion = newState.session.currentQuestion + action.payload;
return newState;
case types.FETCH_PRACTICE_QUESTION:
fetch(action.payload.URL, {
method: 'POST',
body: JSON.stringify({
username: 'student',
password: 'pass1234',
chapter: action.payload.chapter
})
}).
then((response) => response.json()).
then((responseJson) => {
newState.session.questions = responseJson;
newState.session.isLoading = false;
});
console.log(newState);
return newState;
default:
return state;
}
}
现在我的问题是我的QuestionScreen中的props.session保持不变,所以即使在调度该动作之后,加载器仍在继续旋转,我现在该怎么办?
是的还有一件事,我使用logger和thunk中间件检查控制台中的状态状态,打印的状态是预期的,显示我正确值
答案 0 :(得分:1)
您应该使用中间件作为Redux-Thunk来实现异步操作。此外,你不应该在reducer中使用fetch,你应该在请求开始,请求成功和请求错误时调度3个事件。像这样:
export const callApi = ((fetchUrl) => (dispatch) => {
dispatch(requestBegin());
let body = (method === 'GET') ? undefined : JSON.stringify(data);
return fetch(fetchUrl, {
method,
body,
})
.then(checkStatus)
.then(parseJSON)
.then(function(data) {
dispatch(requestSuccess(data);
}).catch(function(error) {
dispatch(requestError(data));
})
});
此外,您还可以阅读有关异步操作here
的信息