簡體   English   中英

React-Native Redux 連接組件未調度動作

[英]React-Native Redux connected component not dispatching actions

我已將我的組件連接到 redux,定義了 mapStateToProps 和 mapDispatchToProps,但調度似乎沒有做任何事情。

當我運行它時,'console.log("Setting token")' 被打印出來,但沒有其他任何反應。 所以 this.props.setToken 正在觸發,因為這是設置 console.log 的地方,但是商店沒有更新,並且 this.props.auth_token 沒有像 dispatch(setToken) 正確觸發時那樣顯示在屏幕上...

應用屏幕

import React from 'react';
import { View, Text, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import { setToken } from './reducer';

class AppScreen extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.setToken("token_abc");
  }

  render() {
    if (this.props.loading) {
      return (
        <View style={{ flex: 1 }}>
          <ActivityIndicator />
        </View>
      )
    } else {
      return (
        <View>
          <Text>You're in! '{this.props.auth_token}'</Text>
        </View>
      )
    }
  }
}

function mapStateToProps(state) {
  return {
    user: state.user,
    auth_token: state.auth_token,
    loading: state.loading,
    error: state.error
  };
}

const mapDispatchToProps = dispatch => {
  return {
    setToken: token => {
      console.log("Setting token")
      dispatch(setToken(token));
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(AppScreen);

減速器

import { createSlice } from "@reduxjs/toolkit";
const appSlice = createSlice({
  name: "app",
  initialState: {
    loading: true,
    auth_token: "",
    error: "",
    user: {}
  },
  reducers: {
    setToken: (state, action) => {
      state.auth_token = action.payload;
      state.loading = false;
    },
  },
  extraReducers: {
  }
});

export const { setToken } = appSlice.actions;
export const appReducer = appSlice.reducer;

店鋪

import { appReducer } from "./App/reducer";
import { configureStore, getDefaultMiddleware } from "@reduxjs/toolkit";

const middleware = [
  ...getDefaultMiddleware(),
]

const store = configureStore({
  reducer: {
    app: appReducer
  },
  middleware,
});

export default store;

您的組合存儲減速器設置與您的mapState嘗試執行的操作不匹配。

您的組件預計state.auth_token將存在。 appSlice.reducer里面有一個auth_token字段。 因此, state.auth_token只有在appSlice.reducer整個 store 的根 reducer 時才會存在。

但是,您當前將appSlice.reducer作為 state.app 的“切片縮減器” state.app ,這將導致state.app.auth_token

您需要通過reducer: appReducer使其本身成為根減速器,或者更新您的mapState以讀取state.app.auth_token

鑒於您可能會有其他切片,我建議使用后一種方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM