我正在使用redux和react redux,无法使用useSelector((函数访问更新的值。
Reducer
导入了Reducer内部的操作
初始化状态
调用Reducer并将状态初始化为初始状态
添加了一个条件语句,用于更新初始状态
import { UPDATE_EMAIL } from "../actions/cred";
const initialState = {
phone: "",
uid: null,
tp: null,
};
const credReducer = (state = initialState, action) => {
// return state;
if (action.type === UPDATE_EMAIL) {
return {
...state,
phone: action.phone,
uid: action.uid,
tp: action.tp,
};
} else {
return state;
}
};
export default credReducer;
操作
export const UPDATE_EMAIL = "UPDATE_EMAIL";
export const updateEmail = (id, uid, tp) => {
return { type: UPDATE_EMAIL, phone: id, uid: uid, tp: tp };
};
创建存储
function Root() {
const [tkn, updateTkn] = useState("");
const [type, updateType] = useState("");
const rootReducer = combineReducers({
auth: credReducer,
});
const store = createStore(rootReducer);
store.subscribe(() => {
console.log("in subscribe");
console.log(store.getState().auth);
updateType(store.getState().auth.tp);
updateTkn(store.getState().auth.phone);
}, []);
return (
<Provider store={store}>
<NavigationContainer>
{tkn === "" || tkn === null ? (
<Auth />
) : type === "doctor" ? (
<Doctor />
) : (
<Vendor />
)}
</NavigationContainer>
</Provider>
);
}
获取存储值
function Home() {
const auth = useSelector((state) => state.auth);
console.log("in home");
console.log(auth);
return (
<View style={styles.box}>
<Ucard />
</View>
);
}
export default Home;
以及最后从上述块得到的输出在此处输入图像描述家庭控制台日志输出
这应该放在组件之外。假设您更新了tkn
或type
状态,然后函数将重新运行,并将再次创建新的存储和根还原器。
存储将再次以初始状态创建,而不是以更新状态创建。
const rootReducer = combineReducers({
auth: credReducer,
});
const store = createStore(rootReducer);
store.subscribe(() => {
console.log("in subscribe");
console.log(store.getState().auth);
updateType(store.getState().auth.tp);
updateTkn(store.getState().auth.phone);
}, []);