设置jsx元素值以获取调用值



我正在制作一个自定义的jsx元素。我想将元素的值设置为数据,获取调用将返回:

const BoardPage = () => {
const id = useParams().id
fetch('http://localhost:8000/getBoardByID', {
headers: {
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ id: id })
}).then(response => response.json()).then(data => {
console.log(data)

return (
<div>
<h1>board #{data.id}</h1>
</div>
)
})
}
export default BoardPage

在控制台中,我看到一个对象:{id: 31, board_content: '', width: 1223, height: 2323, user_privileges: '[]'}
但我没有得到任何输出

您必须在useEffect钩子内执行请求。

const MyComponent = () => {
const id = useParams().id;
const [data, setData] = useState({});
React.useEffect(() => {
fetch("http://localhost:8000/getBoardByID", {
headers: {
"Content-type": "application/json",
},
method: "POST",
body: JSON.stringify({ id: id }),
})
.then((response) => response.json())
.then((data) => {
setData(data);
});
}, []);
return (
<div>
<h1>board #{data?.id}</h1>
</div>
);
};

最新更新