4
在React中,我编写了一个无状态功能组件,现在想要为其添加Prop类型验证。反应:无状态功能组件中的PropType
List
组件:
import React from 'react';
import PropTypes from 'prop-types';
function List(props) {
const todos = props.todos.map((todo, index) => (<li key={index}>{todo}</li>));
return (<ul></ul>);
}
List.PropTypes = {
todos: PropTypes.array.isRequired,
};
export default List;
App
组件,渲染List
:
import React from 'react';
import List from './List';
class App extends React.Component {
constructor() {
super();
this.state = {
todos: '',
};
}
render() {
return (<List todos={this.state.todos} />);
}
}
export default App;
正如你可以看到App
,我传递给this.state.todos
List
。由于this.state.todos
是一个字符串,因此我期望使用Prop Type验证。相反,在浏览器控制台中出现错误,因为字符串没有名为map
的方法。
为什么Prop Type验证不能按预期工作?羚牛看一下this question,案件看起来一样。
快速,方便,谢谢!我只是忽略了那个,哦。 – Sven
要说明这种肮脏的错误,你可以使用https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-typos.md –