reactjs 我在将产品渲染到组件中时遇到问题,产品来自我的redux商店

im9ewurl  于 2023-01-12  发布在  React
关注(0)|答案(1)|浏览(88)

我可以保存产品到我的商店,但我有麻烦呈现它在我的组件.该产品来自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 = ''
        })
);
e4yzc0pl

e4yzc0pl1#

试试看,例如:

//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钩子,并且不需要在本地状态中存储产品)

//example with redux

/ProductDetails.jsx
  const dispatch = useDispatch();
  const { id } = useParams();

  useEffect(() => {
      dispatch(getProduct(id));
  }, [id]);

  const product = useSelector(state=>(....)) //slice with you 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>

相关问题