我职业生涯中第一次开发react应用程序。
所以,我在很多事情上徘徊。。。haaa
我试图通过链接元素在组件之间传递状态
但我确实键入了另一个变量语法。
但我总是在控制台上看到state:null。
并且有许多错误消息"无法读取状态">
<Link to={{pathname:"/movie-detail", state:{year:year, title:title, summary:summary, poster:poster, genres:genres}}}>~~~</Link>
<Link to={"/movie-detail"} state={{year:year, title:title, summary:summary, poster:poster, genres:genres}}>~~</Link>
但我无法移动状态收件人组件。
请教我我的代码出了什么问题。。。
隐藏代码
import React from 'react'
import PropTypes from 'prop-types';
import './Movie.css';
import { Link } from 'react-router-dom';
function Movie({year, title, summary, poster, genres}){
return (
<div className="movie">
<Link to={"/movie-detail"} state={{year:year, title:title, summary:summary, poster:poster, genres:genres}}>
<img src={poster} alt={title} title={title}/>
<div className="movie__data">
<h3 className="movie__title" style={{backgroundColor:'red'}}>{title}</h3>
<h5 className="movie__year">{year}</h5>
<ul className="movie__genres">
{genres.map((genres, index) => {
return (
<li key={index} className="movie__genre">{genres}</li>
);
})}
</ul>
<p className="moive__summary">{summary.slice(0,180)}...</p>
</div>
</Link>
</div>
);
}
Movie.propTypes = {
id:PropTypes.number.isRequired,
year:PropTypes.number.isRequired,
title:PropTypes.string.isRequired,
summary:PropTypes.string.isRequired,
poster:PropTypes.string.isRequired,
genres:PropTypes.arrayOf(PropTypes.string).isRequired,
}
export default Movie;
收件人代码
import React from 'react';
class Detail extends React.Component{
componentDidMount(){
const{location, history} = this.props;
//console.log(this.props);
if(location.state === undefined){
history.push('/');
}
}
render() {
const{location} = this.props;
if(location.state){
return(
<span>{location.state.title}</span>
);
}else{
return null;
};
}
}
export default Detail;
Link
组件有一个to
道具,可以是string
、object
和function
。所以正确的代码是:
<Link to={{ pathname: '/movie-detail', state: { year: year, title: title, summary: summary, poster: poster, genres: genres } }}>~~~</Link>
尝试使用withRouter HOC包装Detail
组件,以便从道具中获得location
和history
对象。
我不建议使用您的路由器来传递数据。理想情况下,您希望根据给定路线从详细信息页面中获取数据(e.g. /movie/star-wars fetches data for post "star-wars" from your server)
。通过分离路由器和组件逻辑,可以保持应用程序的模块性。