javascript - 在渲染从组件中的后端获取的数据时渲染问题
问题描述
我遇到了重新渲染错误的问题!
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
},
...
我刚刚从后端获取了一些数据并使用 auseState
来存储将要映射的结果数组,以便使用Storyfeed组件显示每个故事数据,这也是响应,它提供了一个对象数组,我想要映射它们,以便我可以显示它们
解决方案
我相信你试图不通过尝试对前一个状态值进行连接来干扰状态的前一个值。试试下面
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
推荐阅读
- javascript - 从javascript中的按钮在onclick window.location上添加一个php GET变量
- bash - 如何使用 sed/awk 在十六进制数之间添加零?
- statistics - 哪个模型应该用于(事件百分比,时间)预测。分布不是线性的
- c - 循环线程中的 pthread_barrier_t
- html - 从 git 克隆后,我的 web 界面发生了一些变化
- python - 等待使用 Python (iframe) 在 Selenium 中可点击
- java - 正则表达式更改电话号码的形式
- javascript - 从另一个组件重新渲染组件的一部分
- c# - 困惑:抽象类属性
- google-chrome - 流行浏览器中的 Webcryto getRandomValues() 实现