我是一个新手开发者,请告诉我为什么在调用 initPayment 时会出现错误:“在操作中检测到不可序列化的值,路径:payload。值:[错误:无效的钩子调用。只能调用钩子”功能组件主体内部]”
import { useSQLiteContext } from "expo-sqlite";
const paymentSlice = createSliceWithThunks({
name: "payments",
initialState,
reducers: (create) => ({
initPayment: create.asyncThunk(
async function (_, { rejectWithValue }) {
try {
const db = useSQLiteContext();
const payments = await db.getAllAsync<Payments>("SELECT * FROM payments");
return payments;
} catch (err) {
return rejectWithValue(err);
}
},
{
fulfilled: (state, action: PayloadAction<Payments[]>) => {
state.list = action.payload;
},
rejected: (state) => {
console.error("Error");
},
}
),
}),
});
export default function Main() {
const { theme } = useContext(ThemeContext);
return (
<SQLiteProvider
databaseName="payments.db"
assetSource={{ assetId: require("../assets/payments.db") }}
>
<Provider store={store}>
<NavigationContainer theme={theme}>
<PaperProvider>
<StatusBar style="auto" />
<Stack.Navigator
screenOptions={{
contentStyle: {
backgroundColor: theme.colors.background,
padding: 20,
},
headerShadowVisible: false,
headerStyle: {
backgroundColor: theme.colors.background,
},
}}
>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Payment" component={Payment} />
</Stack.Navigator>
</PaperProvider>
</NavigationContainer>
</Provider>
</SQLiteProvider>
);
}
除了 React 函数和自定义 React hook 之外,您无法从任何 调用 React hook,因此在
useSQLiteContext
操作创建器中调用 initPayment
是无效的。
您可以但是在正在调度
useSQLiteContext
的React组件中调用initPayment
并将数据库实例传递给Thunk操作。
示例:
const paymentSlice = createSliceWithThunks({
name: "payments",
initialState,
reducers: (create) => ({
initPayment: create.asyncThunk(
async function ({ db }, { rejectWithValue }) {
try {
return db.getAllAsync<Payments>("SELECT * FROM payments");
} catch (err) {
return rejectWithValue(err);
}
},
{
fulfilled: (state, action: PayloadAction<Payments[]>) => {
state.list = action.payload;
},
rejected: (state) => {
console.error("Error");
},
}
),
}),
});
import { useSQLiteContext } from "expo-sqlite";
...
const SomeComponent = () => {
const dispatch = useDispatch();
const db = useSQLiteContext();
...
const someHandler = async () => {
...
const payments = await dispatch(initPayment({ db })).unwrap();
...
};
...
};