gpt4 book ai didi

javascript - react 路由器 : Data fetched using axios doesn't save when navigating to new route

转载 作者:行者123 更新时间:2023-11-30 19:06:42 24 4
gpt4 key购买 nike

我正在使用 react-router-dom 构建一个 React 应用程序并从我的 Django Rest Framework 后端获取数据,一旦数据被获取,我导航到另一个链接,数据保存到 window 并在内部保存 inside state 被删除。我如何在客户端中保存这些数据?

代码如下:

路由器

import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import AuthHeader from './authheader';
import { BlogData, BlogDetail } from '../components/blog';



export default class AuthRouter extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: false,
authtoken: '',
}
}

handler = (token) => {
this.setState({
isLoggedIn: true,
authtoken: token,
})
}
/**
* ! Render the Route props inside of the
* ! BlogData component
*/

render () {
return (
<Router>
<div>
{/* <Header /> */}
{/* <Route path='/home' exact component={WrappedHorizontalLoginForm} /> */}
{/* <Route path='/about' exact component={AuthHeader} /> */}
<AuthHeader
action={this.handler}
token={this.state.isLoggedIn && this.state.authtoken}
/>
<Route
path='/blog'
exact
render={(props) => <BlogData {...props}
token={this.state.isLoggedIn && this.state.authtoken}
/>} />
<Route
path='/blog/:id'
exact
render={(props) => <BlogDetail {...props}
token={this.state.isLoggedIn && this.state.authtoken}
/>} />
</div>
</Router>
);
}
}

Authheader 组件最终将 props 传递给 LoginFormOrUserComponent :

import React, { Component } from 'react';
import axios from 'axios';
import Button from 'react-bootstrap/Button';
import Form from 'react-bootstrap/Form';
import { localhost, authtoken } from '../backendUrlConstants';
import Col from 'react-bootstrap/Col';

export default class LoginFormOrUserComponent extends Component {

constructor(props) {

super(props);

this.state = {
isLoggedIn: false,
authtoken: null,
username: '',
password: '',
}

// if (this.props.token) {
// this.setState({ authtoken: this.props.token })
// this.setState({ isLoggedIn: true })
// }
}

// componentDidMount (props) {
// if (this.props.token) {
// this.setState({ authtoken: this.props.token })
// this.setState({ isLoggedIn: true })
// }
// }

passAuthTokenToParentClass = () => {

const { authtoken } = this.state;
if (authtoken) {
this.props.action(authtoken)
}
}

handleUsernameChange = (e) => {
this.setState({ username: e.target.value })
}

handlePasswordChange = (e) => {
this.setState({ password: e.target.value })
}

handleSubmit = (e) => {
console.log(e)
const username = this.state.username;
const password = this.state.password;
axios.post(`${localhost}${authtoken}`, { username, password })
.then(res => {
this.setState({ authtoken: res.data.token })
this.setState({ isLoggedIn: true })
this.passAuthTokenToParentClass()
})
// TODO: Catch the error if the username and password
// TODO: are incorrect.
}

renderLoginFormOrUserComponent = () => {
if (this.state.isLoggedIn === false) {
return <Form className="mr-auto" >
<Form.Row>
<Col xs={4}>
<Form.Control placeholder="Username" onChange={this.handleUsernameChange} />
</Col>
<Col xs={4}>
<Form.Control placeholder="Password" onChange={this.handlePasswordChange} />
</Col>
</Form.Row>
<Button variant="dark" onClick={this.handleSubmit} >Submit</Button>
</Form>
}
return <Button variant="dark" >Account</Button>
}

render () {

return (
this.renderLoginFormOrUserComponent()
);
}
}

下面是 BlogDataBlogDetail 组件:

import React, { Component } from 'react';
import axios from 'axios';
import { localhost } from '../backendUrlConstants';
import { Link } from 'react-router-dom';
import { Card } from 'react-bootstrap';


export class BlogData extends Component {

constructor(props) {
super(props);
this.state = {
data: [],
}
}

getUrl () {
return this.props.location.pathname
}

componentDidMount () {
const uri = this.getUrl()
axios.get(`${localhost}${uri}`)
.then(res => {
const data = res.data;
this.setState({ data })
})
}

render () {
return (
<ul>
{this.state.data.map(
data => <li key={data.id} >
<Link to={`/blog/${data.id}`} >{data.url}</Link>
</li>
)}
</ul>
)
}
}

export class BlogDetail extends BlogData {

constructor(props) {

super(props)
this.state = {
blogObject: {}
}
}

componentDidMount () {
const uri = this.getUrl()
axios.get(`${localhost}${uri}`)
.then(res => {
const data = res.data;
this.setState({ blogObject: data })
})
}

render () {

const { blogObject } = this.state;
return (
<Card style={{ width: "18rem" }} >
<Card.Img variant="top" src={blogObject.blog_picture_context} />
<Card.Body>
<Card.Title>{blogObject.blog_name}</Card.Title>
<Card.Text>{blogObject.blog_post}</Card.Text>
</Card.Body>
</Card>
)
}
}

此外,这里的上下文是我的本地主机 Django 服务器的 url:

export const localhost = 'http://127.0.0.1:8000';
export const login = '/api-auth/login/';
export const authtoken = '/authtoken/';

一旦我从后端获取数据,一旦我导航到另一个页面,我就会丢失它。显然我在这里缺少一些东西。

最佳答案

使用 Hook ,您可以在导航到通常会刷新状态的新 URL/链接时轻松传递数据。无需使用本地存储或类似的东西。

例如,我有一个管理仪表板,其中包含用户的嵌套路由,我希望用户的 url 成为用户 id,我想将用户 id 传递给新 url 并能够在其中使用它新组件。

我的嵌套路由文件如下所示:

import React from 'react';
import { Index, SignIn, SignUp } from '../onepirate/';
import { Admin, Event, CheckoutPath, Profile, Tickets, CheckoutComplete } from '../screens/';
import AdminDashboard from '../components/admin/AdminDashboard';
import UserAccount from '../screens/admin/user-components/UserAccount'
import Users from '../screens/admin/Users';

const adminRoutes = {
"/dashboard": () => <AdminDashboard />,
"/events": () => <Event />,
"/users": () => <Users />,
"/users/:userId": ({ userId }) => <UserAccount userId={userId} />,
}

export default adminRoutes;

如您所见,我从/users 组件传递用户 ID,并将其作为属性通过路由发送。同时,用户 ID 将动态地包含在 URL 中。

然后将路由器导入到应该处理路由的组件中:

import { useRoutes, useRedirect, navigate } from 'hookrouter';
export default function Admin() {
// this function allows your to redirect from one URL to another
useRedirect('/admin', '/admin/dashboard');

return (
<main className={classes.content}>
<Container>
{router}
</Container>
</main>
</div>
);
}

然后作为示例从我的用户组件导航到 users/:userID

import { useRoutes, useRedirect, navigate } from 'hookrouter';

const User = props => {
const classes = useStyles();

return (
<Container>
<Paper className={classes.root}>
<TextField
id="outlined-search"
label="Search field"
type="search"
className={classes.textField}
margin="normal"
variant="outlined"
onChange={props.search}
/>
<Table className={classes.table}>
<TableHead className={classes.tableHead}>
<TableRow className={classes.tableHead}>
<TableCell className={classes.tableHead} align="">Id</TableCell>
<TableCell className={classes.tableHead} align="">Email</TableCell>
<TableCell className={classes.tableHead} align="">First Name</TableCell>
<TableCell className={classes.tableHead} align="">Last Name</TableCell>
<TableCell className={classes.tableHead} align="">Info</TableCell>
</TableRow>
</TableHead>
<TableBody>
{props.data.map((user, index) => (
<TableRow key={index}>
<TableCell align="right">{user.id}</TableCell>
<TableCell align="right">{user.email}</TableCell>
<TableCell align="right">{user.firstname}</TableCell>
<TableCell align="right">{user.lastname}</TableCell>

// be sure to pass the user id in the navigate() function

<TableCell><AccountBoxIcon onClick={() => (navigate("/admin/users/" + user.id))}></AccountBoxIcon></TableCell>
</TableRow>
))}
</TableBody>

</Table>
</Paper>
</Container>
)
}
export default User;

然后在 UserAccount 组件中链接到我们的路由文件并将用户 ID 传递给,我们可以看到控制台传递的数据将 props 记录在 useEffect(组件将挂载等效) Hook 中。

//用户帐户组件:

useEffect(() => {
// userId we sent as prop through route
console.log(props.userId);
// ... do cool things
}, []);

关于javascript - react 路由器 : Data fetched using axios doesn't save when navigating to new route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58907665/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com