繁体   English   中英

为什么我无法通过Link组件访问state?

[英]Why Am I Not Able to Access state Through a Link Component?

我已经尝试对此代码片段进行大量小的更改(额外的花括号,将链接组件代码中的 ':' 更改为 '=',仍然 location.state 是 null 在我试图传递的 ReportEdit 组件上state to. 这在 React Router Dom 6.2.1 中不是可能的吗?

这是代码

绘制链接的组件

<Link 
  to={`/report/${report.id}/edit`}
  state={{hi: "hi"}}>
 <Button>
    Edit
 </Button>
</Link>

我想将 state 传递给的链接组件

import { Form, Button } from 'react-bootstrap'
import { Link, useParams, useLocation } from 'react-router-dom'
import axios from 'axios';

const ReportEdit = props => {

  const [report, setReport] = useState([]);
  const [ rep_type, setRepType ] = useState(report.rep_type);
  const [ rep_count, setRepCount ] = useState(report.rep_count);

  let params = useParams()
  const location = useLocation()

  console.log(location.state) // <--- always 'null'

  const id = params.id

  //async function handleSubmit() {
    //let data = await axios.put(`http://localhost:3001/reports/${id}`)
   // if (data) {
     // console.log(data.data.report)
    //}
  //}

  return (
    <div>
      <Form onSubmit={e => handleSubmit(e)}>
        <Form.Group className="mb-1" controlId="rep_type">
          <Form.Control 
            type="text" 
            placeholder={props.rep_type}
            name="rep_type"
            value={rep_type}
            onChange={e => setRepType(e.target.value)} 
          />
        </Form.Group>

        <Form.Group className="mb-1" controlId="rep_count">
          <Form.Control 
            type="number" 
            placeholder={props.rep_count} 
            name="rep_count"
            value={rep_count} 
            onChange={e => setRepCount(e.target.value)} 
          />
        </Form.Group>
      <Button variant="primary" type="submit">Submit</Button>
    </Form>
  </div>
  )
}

export default ReportEdit;

可以参考官方react-router-dom文档,可以通过object传递params,例如:

<Link
  to={{
    pathname: `/report/${report.id}/edit`,
    state: { id: report.id }
  }}
/>

我想到了。

我只是在开发中刷新目标页面,实际上我需要使用链接通过 state 传递道具。 fml。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM