【问题标题】:I have a problem to render product into my component, the product came from my redux store我在将产品渲染到我的组件中时遇到问题,该产品来自我的 redux 商店
【发布时间】:2023-01-12 20:00:38
【问题描述】:

我可以将产品保存到我的商店中,但我无法在我的组件中呈现它。 该产品来自 api 调用并存储在我的 redux 商店中。 问题出在我的组件中,但也许我的商店有问题?

//ProductDetails.jsx

  const dispatch = useDispatch();
  const { id } = useParams();
  const [product, setProduct] = useState(null);

  useEffect(() => {
    async function fetchProduct() {
      const response = await dispatch(getProduct(id));
      setProduct(response.payload);  //the app stack when i write this line

    }
    fetchProduct();
  }, [id , product]);

  return (
    <div className="details-container">
      {!product ? (
        <ClipLoader color={"#36d7b7"} loading={loading} size={35} />
      ) : (
        <div className="img-container">
          <img src={product.img} alt={product.brand} />
        </div>
      )}
    </div>
//productsSlice.jsx

export const getProduct = createAsyncThunk("products/getProduct", async (id) => {
    const prod = await productsService.getProductById(id);
    return prod
    },

        builder.addCase(getProduct.fulfilled, (state, action) => {
            state.loading = false
            state.currProduct = action.payload
            // state.error = ''
        })
);

【问题讨论】:

    标签: reactjs redux react-hooks react-redux redux-toolkit


    【解决方案1】:

    试试看,例如:

    //ProductDetails.jsx
      const { id } = useParams();
      const [product, setProduct] = useState(null);
    
      useEffect(() => {
        async function fetchProduct() {
          const response = await productsService.getProductById(id);
          setProduct(response.payload);
    
        }
        fetchProduct();
      }, [id , product]);
    
      return (
        <div className="details-container">
          {!product ? (
            <ClipLoader color={"#36d7b7"} loading={loading} size={35} />
          ) : (
            <div className="img-container">
              <img src={product.img} alt={product.brand} />
            </div>
          )}
        </div>
    

    现在您可以混合使用 useState 和 Redux。

    选择一个流 useState 或 Redux。 (在 Redux 的情况下你错过了 useSelector 钩子并且不需要在本地状态存储产品)

    【讨论】:

    • 我使用 redux flow,但首先我需要将操作分派给 redux right (useDispatch) 对吗?
    猜你喜欢
    • 2021-09-22
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2021-11-15
    • 1970-01-01
    • 2019-01-31
    相关资源
    最近更新 更多