me-*_*-me 5 reactjs react-proptypes
我在其match> params对象中从React路由器传递了道具,我希望在我的静态propTypes中将其设置为必需的字符串值.当我将其设置为照片时:PropTypes.string.isRequired我收到错误.
Warning: Failed prop type: The prop `photo` is marked as required in `BlogEntry`, but its value is `undefined`.
Run Code Online (Sandbox Code Playgroud)
当我通过路由器道具记录下来的内容时,我可以看到照片是一个字符串ID.
const {match:{params:{photo}}} = this.props;
console.log("photo = ", photo);
// result:
photo = 5a03c474e1bbc026de896aa8
Run Code Online (Sandbox Code Playgroud)
有没有办法在照片上进行必要的类型验证?
这是我的设置.
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);
Run Code Online (Sandbox Code Playgroud)
如果你想输入检查照片并且它来自React Router,你必须改变你的道具以期望它匹配.
例如,如果我想键入检查props.match.params.name我的proptypes将是:
match: PropTypes.shape({
params: PropTypes.shape({
name: PropTypes.string.isRequired
})
}),
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3690 次 |
| 最近记录: |