我在其匹配中从React路由器传递了道具> params对象,我想在我的静态propTypes中设置为必需的字符串值。 当我将其设置为照片时:PropTypes.string.isRequired我收到错误。
Warning: Failed prop type: The prop `photo` is marked as required in `BlogEntry`, but its value is `undefined`.
当我通过路由器道具记录下来的内容时,我可以看到照片是一个字符串ID。
const {match:{params:{photo}}} = this.props;
console.log("photo = ", photo);
// result:
photo = 5a03c474e1bbc026de896aa8
有没有办法在照片上进行必要的类型验证?
这是我的设置。
import React, {Component} from 'react';
import {connect} from 'react-redux';
import PropTypes from 'prop-types';
import {fetchBlogEntry} from '../../actions/index';
import BlogPost from '../../components/client/blog-post';
class BlogEntry extends Component{
constructor(props){
super(props);
console.log('constructor = ', this.props.match.params.photo);
}
static propTypes={
entry: PropTypes.object.isRequired,
photo: PropTypes.string.isRequired
}
componentWillMount(){
const {match:{params:{photo}}} = this.props;
console.log("photo = ", photo);
this.props.fetchBlogEntry(photo);
}
render(){
const {entry} = this.props;
return(
<div id='blog' className='container'>
<BlogPost {...entry}/>
</div>
)
}
}
function mapStateToProps({blog:{entry}}){
return{
entry
}
}
export default connect(({blog:{entry}}) => ({entry}), {fetchBlogEntry})(BlogEntry);
答案 0 :(得分:5)
如果你想输入检查照片并且它来自React Router,你必须改变你的道具以期望它匹配。
例如,如果我想键入check props.match.params.name
我的proptypes
将是:
match: PropTypes.shape({
params: PropTypes.shape({
name: PropTypes.string.isRequired
})
}),