为什么我的函数没有在react组件中调度?



为什么fetchReviews不抓取?最初没有使用fetchData在使用效果。我试过使用useDispatch。将BusinessId传递给星型组件。控制台没有错误。如果还有其他需要看的文件,请告诉我。谢谢你!

星组件:

import React, { useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import {AiFillStar } from "react-icons/ai";
import { fetchReviews } from '../../actions/review_actions';
function Star(props) {
const [rating, setRating] = useState(null);
// const [reviews, setReview] = useState(props.reviews)
// const dispatch = useDispatch();
useEffect(() => {
const fetchData = async () => {
await fetchReviews(props.businessId)
};
fetchData();
console.log(props);
// getAverageRating();
});
const getAverageRating = () => {
let totalStars = 0;
props.reviews.forEach(review => {totalStars += review.rating});
let averageStars = Math.ceil(totalStars / props.reviews.length);
setRating(averageStars);
}
return (
<div className='star-rating-container'>
{Array(5).fill().map((_, i) => {
const ratingValue = i + 1;
return (
<div className='each-star' key={ratingValue}>
<AiFillStar
className='star'
color={ratingValue <= rating ? '#D32322' : '#E4E5E9'}
size={24} />
</div>
)
})}
</div>
);
};
export default Star;

star_container:

import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import Star from "./star";
import { fetchReviews } from "../../actions/review_actions";
const mSTP = state => {
return {
reviews: Object.values(state.entities.reviews)
};
}
const mDTP = dispatch => {
return {
fetchReviews: businessId => dispatch(fetchReviews(businessId))
};
};
export default connect(mSTP, mDTP)(Star);

控制台图片

为什么fetchReviews不抓取?最初没有使用fetchData在使用效果。我试过使用useDispatch。将BusinessId传递给星型组件。控制台没有错误。

编辑!* * *

做了一些更改并添加了useDispatch。现在它不会停止运行。它总是在抓取。

function Star(props) {
const [rating, setRating] = useState(null);
const [reviews, setReview] = useState(null)
const dispatch = useDispatch();
useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};
fetchData();
// console.log(props);
// getAverageRating();
}), [];

最终只是使用useEffect中的ajax调用。

useEffect(() => {
const fetchReviews = (businessId) =>
$.ajax({
method: "GET",
url: `/api/businesses/${businessId}/reviews`,
});
fetchReviews(props.businessId).then((reviews) => getAverageRating(reviews));
}), [];

如果有人知道我如何清理和使用调度lmk。ty。

useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};    
fetchData();
// console.log(props);
// getAverageRating();
}), [];

依赖数组在useEffect之外。由于useEffect没有传递依赖项选项,useEffect内部的函数将在每次渲染中运行,并且在每次渲染中您保持调度动作,这会改变渲染组件的存储,因为它渲染useEffect内部的代码运行

// pass the dependency array in correct place
useEffect(() => {
const fetchData = async () => {
const data = await dispatch(fetchReviews(props.businessId))
setReview(data);
};    
fetchData();
// console.log(props);
// getAverageRating();
},[]), ;

传入空array[]意味着,useEffect中的代码将只在组件挂载前运行一次

相关内容

  • 没有找到相关文章

最新更新