reactjs 类型为"string"的参数|不能将"null"赋给类型为"string"的参数[重复]

fae0ux8s  于 2023-01-02  发布在  React
关注(0)|答案(2)|浏览(363)
    • 此问题在此处已有答案**:

Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'(10个答案)
昨天关门了。


关于代码有一个错误是"类型'字符串的参数|"null"不能赋给类型为"string"的参数。"
定义的函数为:

export const getShoppingCart = createAsyncThunk(
  "shoppingCart/getShoppingCart",
  async (jwt: string, thunkAPI) => {
    const { data } = await axios.get(
      `https://e9e0fde5-0f50-4037-af58-6b187be97f69.mock.pstmn.io/shoppingCart`,
      {
        headers: {
          Authorization: `bearer ${jwt}`,
        },
      }
    );
    return data.shoppingCartItems;
  }
);

存储类型为:

interface ShoppingCartState {
  loading: boolean;
  error: string | null;
  items: any[];
}

const initialState: ShoppingCartState = {
  loading: true,
  error: null,
  items: [],
};

切片为:

export const shoppingCartSlice = createSlice({
  name: "shoppingCart",
  initialState,
  reducers: {},
  extraReducers: {
    [getShoppingCart.pending.type]: (state) => {
      state.loading = true;
    },
    [getShoppingCart.fulfilled.type]: (state, action) => {
      state.items = action.payload;
      state.loading = false;
      state.error = null;
    },
    [getShoppingCart.rejected.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.loading = false;
      state.error = action.payload;
    }
   }
  })

我的问题是有没有更规范的解决方案?我正在了解,谢谢!
我可以通过三元运算符修复它。像这样:

useEffect(() => {
    dispatch(getShoppingCart(jwt ? jwt : ''))
  }, [jwt, dispatch])
643ylb08

643ylb081#

'字符串|"null"不能赋给"string"类型的参数
因为user.tokenstring | null,所以不能将其用于getShoppingCart(预期为string

修复

如果您确定它不为空,则可以使用非空Assert,即getShoppingCart(jwt!)

更多

  • 非空Assert
kgsdhlau

kgsdhlau2#

首先我要感谢帮助过我的人。虽然没有帮我解决问题。但是给了我一个不同的思考方式。总有那么两个自以为是的人,他们不仅不提供帮助,但是少给予我2分。2看来我高估了这个网站。3最后我自己解决了这个问题。4和你们还有那两个自以为是的人分享一下。请把我宝贵的积分还给我,别指望0+,0就行了!

const jwt = useSelector((s) => s.user.token) as string
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(getShoppingCart(jwt))
  }, [jwt, dispatch])

相关问题