在组件中呈现从后端提取的数据时出现呈现问题



我遇到了重新渲染错误的问题!

import React , {useEffect} from 'react'
import "./UsernameStory.css";
import Axios from "axios";
import Storyfeed from '../storySmall/Storyfeed';


const UsernameStory = ({match}) => {
const [statue , setStatue] = React.useState("");
const [storie , setStorie] = React.useState([]);
useEffect(() => {
const urls = match.params.username;
Axios.post("http://localhost:8080/user/"+urls, {})
.then((response) => {
if(response.data.statue)
{
setStatue(response.data.statue);
}
if(response.data){
setStorie(storie.concat(response.data));
}
});
}, []); // An empty denpendency array allows you to fetch the data once on mount

return (
<div>
<p>{statue}</p>
{storie.map((story , key) => (<Storyfeed key = {key}  story = {story}/>))}
</div>
)
}
export default UsernameStory

Storyfeed.js

import React , {useEffect}from 'react'
import Axios from "axios";
import {Link} from "react-router-dom";
import NotFound from '../../errors/404/NotFound';
import ThumbUpIcon from '@material-ui/icons/ThumbUp';
const Storyfeed = ({story}) => {
const [votes , setVotes] = React.useState(story.vote);
const [link , setLink] = React.useState("");
setLink(story.link)
let url = `/story/${link}`;
return(
<div className = "story">
<p>{story.username}</p>
<Link to={url}><p>{story.title}</p></Link>
<div className = "votes">
<ThumbUpIcon />
<p> Total Votes : {votes}</p>
</div>
</div>
);
}

这是的响应

response.data = [{
email: "mouadpro3@gmail.com",
id: 7,
link: "hello-world",
story: "test",
title: "hello world",
username: "MH15O",
votes: 0
},
...

我刚刚从后端获取了一些数据,并使用useState存储将要映射的结果数组,以便使用Storyfeed组件显示每个故事的一些数据这也是响应,它给出了一个对象数组,我想映射它们,这样我就可以向它们显示

我相信您试图通过对上一个状态值进行concat来避免干扰状态的上一个值。尝试以下

response.data = [{
email: "mouadpro3@gmail.com",
id: 7,
link: "hello-world",
story: "test",
title: "hello world",
username: "MH15O",
votes: 0
},
{...},
{...}];

对于您的回复,我已经更新了答案

const UsernameStory = ({match}) => {
const [statue, setStatue] = React.useState("");

const [story, setStory] = React.useState([]);

const setMyStory = (sto) => setStory([...story, sto]);

or

const setMyStory = (sto) => setStory(prevState => [...prevState, sto]);
useEffect(() => {
const urls = match.params.username;
Axios.post("http://localhost:8080/user/"+urls, {})
.then((response) => {
if( response.data && response.data[0].statue){
setStatue(response.data[0].statue);
} else if(response.data && response.data[0].story) {
setMyStory(response.data[0])
}
});
}, []); 

return (
<div>
<p>{statue}</p>
{story.map((story , key) => (<Storyfeed key = {key}  story = {story}/>))}
</div>
)
}
export default UsernameStory

最新更新