[英]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.