首页 文章

使用redux结构执行任务后,组件未在react-native中更新

提问于
浏览
1

我正在使用react-native构建一个应用程序,遵循redux概念,现在我遇到了问题,我的组件在调度操作后没有按照它们应该更新 .

稍微解释一下,我有一个React类“QuestionScreen”,我希望在页面打开后立即调用API,但是在API执行工作时应该呈现加载器,当它完成时,问题应该出现.so这是我的代码如下

PS:我是新的反应原生和超新的redux概念,所以一点帮助解释会很好

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中间件检查控制台中的状态状态,打印的状态是预期的,显示我正确的 Value

1 回答

  • 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

相关问题