组件正在更新状态,但不强迫重新渲染 - 相反,它正在添加到状态,只是将更多数据添加到页面
编辑以显示slice*
我是一名学生,我正在使用Reddit的JSON API进行Reddit类型网站。像reddit一样,主屏幕显示提要,我在侧面有一个子列表列表。当您单击其中一个子列数时,主供稿需要为该特定的子reddit显示提要。 API调用正常工作,我的路线参数似乎正常。但是,虽然使用效率注意到URL正在发生变化,并提出获取请求以获取适当的数据,但组件不会重新渲染。相反,它只是将新数据添加到先前的状态。因此,例如,如果我单击“主页”链接,则提要将显示正确的“主页”数据...但是,如果我单击另一个子雷迪特(如有趣的动物),它将保留家庭供稿并添加“”并添加“”有趣的动物”到家庭饲料的尽头。国家从不刷新,它只是生长。
我已经强制了一个完整的刷新(使用标签而不是我通过参数的标签),并且一切都按预期工作了……但是,当然,我宁愿处理React中的更改。
我需要在此项目中使用Redux工具包,所以这可能是与商店互动的问题?
我已经阅读了文档,并在网上环顾了,但是我只是不确定我应该寻找什么,因为我似乎已经击中了死者。其中有些有点
让我感到沮丧了几天,所以我感谢任何帮助!
这是代码:
export default function SubReddit() {
const [loading, setIsLoading] = useState(false)
const dispatch = useDispatch()
const { name } = useParams()
let url = 'https://www.reddit.com/r/' + name + '.json'
const posts = useSelector(selectPosts)
// const { loading } = useSetData(url)
const postData = async () => {
setIsLoading(true)
try {
const response = await fetch(url);
if (response.status === 200) {
const jsonResponse = await response.json();
console.log(jsonResponse)
const newData = jsonResponse.data.children
//create new object to be stored in Redux and dispatch to store
newData.map((item) => {
dispatch(setData({
id: item.data.id,
title: item.data.title,
author: item.data.author,
comments: item.data.num_comments,
subreddit: item.data.subreddit_name_prefixed,
url: item.data.url,
text: item.data.selftext,
media: item.data.media,
img: (typeof (item.data.preview) !== 'undefined') ? item.data.preview.images[0].source.url.replace("amp;", "") : null
}))
})
setIsLoading(false)
}
} catch (error) {
console.log(error)
setIsLoading(false)
} finally {
setIsLoading(false);
}
}
useEffect (() => {
postData()
}, [url])
return (
<div className="feed-container">
{posts.map(post => (
<FeedCard key={post.id} image={post.image} title={post.title} url={post.url} media={post.media} text={post.text} author={post.author} comments={post.comments} />
))}
</div>
)
}
这是切片:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {posts:[]}
export const dataSlice = createSlice({
name: 'posts',
initialState,
reducers: {
setData: (state, action) => {
// console.log(action.payload)
state.posts.push({
id: action.payload.id,
title: action.payload.title,
author: action.payload.author,
comments: action.payload.comments,
subreddit: action.payload.subreddit,
url: action.payload.url,
text: action.payload.text,
image: action.payload.img,
media: action.payload.media
})
},
}
}
)
export default dataSlice.reducer;
export const { setData } = dataSlice.actions;
export const selectPosts = state => state.data.posts;
Edited to show slice*
I am a student, and I am making a Reddit type site using Reddit's JSON API. Like Reddit, the main screen shows the feed, and I have a list of subreddits on the side. When you click on one of those subreddits, the main feed needs to show the feed for that particular subreddit. The API call works just fine and my route params seem to work just fine. However, while useEffect is noticing that the url is changing and makes the fetch request to get the appropriate data, the component doesn't re-render. Instead, it just adds the new data to the previous state. So, for example, if I click on the "home" link, the feed displays the correct "home" data...but then if I click on another subreddit (like funny animals), it keeps the home feed and adds the "funny animals" to the end of the home feed. The state never refreshes, it just grows.
I have forced a complete refresh (using tags instead of tags in the subreddit list where I pass the params), and everything works as intended...but of course, I'd rather deal with the change within React.
I am required to use Redux Toolkit for this project, so maybe it's an issue with how I'm interacting with the store?
I have read through documentation and have looked around online, but I am just not entirely sure what I should be looking for anymore since I seem to have hit dead ends. Some of it is a bit
This has frustrated me for a couple of days now, so I would appreciate any help!!
Here is the code:
export default function SubReddit() {
const [loading, setIsLoading] = useState(false)
const dispatch = useDispatch()
const { name } = useParams()
let url = 'https://www.reddit.com/r/' + name + '.json'
const posts = useSelector(selectPosts)
// const { loading } = useSetData(url)
const postData = async () => {
setIsLoading(true)
try {
const response = await fetch(url);
if (response.status === 200) {
const jsonResponse = await response.json();
console.log(jsonResponse)
const newData = jsonResponse.data.children
//create new object to be stored in Redux and dispatch to store
newData.map((item) => {
dispatch(setData({
id: item.data.id,
title: item.data.title,
author: item.data.author,
comments: item.data.num_comments,
subreddit: item.data.subreddit_name_prefixed,
url: item.data.url,
text: item.data.selftext,
media: item.data.media,
img: (typeof (item.data.preview) !== 'undefined') ? item.data.preview.images[0].source.url.replace("amp;", "") : null
}))
})
setIsLoading(false)
}
} catch (error) {
console.log(error)
setIsLoading(false)
} finally {
setIsLoading(false);
}
}
useEffect (() => {
postData()
}, [url])
return (
<div className="feed-container">
{posts.map(post => (
<FeedCard key={post.id} image={post.image} title={post.title} url={post.url} media={post.media} text={post.text} author={post.author} comments={post.comments} />
))}
</div>
)
}
Here is the slice:
import { createSlice } from "@reduxjs/toolkit";
const initialState = {posts:[]}
export const dataSlice = createSlice({
name: 'posts',
initialState,
reducers: {
setData: (state, action) => {
// console.log(action.payload)
state.posts.push({
id: action.payload.id,
title: action.payload.title,
author: action.payload.author,
comments: action.payload.comments,
subreddit: action.payload.subreddit,
url: action.payload.url,
text: action.payload.text,
image: action.payload.img,
media: action.payload.media
})
},
}
}
)
export default dataSlice.reducer;
export const { setData } = dataSlice.actions;
export const selectPosts = state => state.data.posts;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的还原器正在按照您的期望工作。因此,您需要的是重置降低器,以在使用使用效率挂钩中调用PostData()函数之前重置商店的状态。由于您能够看到帖子的增长,因此成功完成了该组件的重新设计。
这里更多信息:
https://bionicicjulia.com/blog/清晰的Redux-Toolkit-State-with-redux-persist and typecript
Your reducer is working as you expect. So what you need is a resetState reducer to reset the state of your store before you call the postData() function in your useEffect hook. Rerendering of the component is done successfully since you were able to see the posts grow.
More information here:
https://bionicjulia.com/blog/clear-redux-toolkit-state-with-redux-persist-and-typescript