上下文:
我写了一个简单的包装器来自动绑定(bind) Prop 。
代码:
只需使用 create-react-app
创建一个新应用,并将 App.js
替换为以下内容:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function Binder ({allState, children}) {
const child = React.Children.only(children);
return React.cloneElement(child, {
name: allState.name,
age: allState.age
});
}
function People ({name, age}) {
return(
<div>
<p>name: {name}</p>
<p>age: {age}</p>
</div>
);
}
class App extends Component {
constructor() {
super();
this.state = {
name: 'albert',
age: 99
};
}
render() {
return (
<div className="App">
<Binder allState={this.state}>
<People />
</Binder>
</div>
);
}
}
export default App;
App
是主要入口,Binder
是将 state
绑定(bind)到 People
的包装器。
问题:
在我添加 propTypes
之前,一切都完美无缺,
People.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
即使是 React 开发工具显示 People
确实收到了两个所需的 prop
,它仍然会打印以下警告:
Warning: Failed prop type: The prop
name
is marked as required inPeople
, but its value isundefined
. in People (at App.js:38) in App (at index.js:7)Warning: Failed prop type: The prop
age
is marked as required inPeople
, but its value isundefined
. in People (at App.js:38) in App (at index.js:7)
如何克服这个问题?:
我发现克服这个问题的唯一方法是删除 isRequired
,然后分配默认属性。或者简单地删除 PropTypes
。
为什么?:
感觉不对。
自动绑定(bind)时我在做什么吗?
为什么它在收到值时打印警告,似乎在初始化时没有收到值?
处理这个问题的最佳方法是什么?
谢谢!
最佳答案
发出警告是因为您正在实例化 <People>
在App.render()
甚至在 Binder
之前有机会克隆元素。
一个可能的解决方案是传递组件(类/函数)的类型,而不是实例,并让Binder
实例化。
const { child } = this.props;
return React.createElement(child, {
name: allState.name,
age: allState.age
});
或:
const { child: Child } = this.props;
return (<Child name={allState.name} age={allState.age} />);
关于javascript - 为什么自动绑定(bind)的 Prop 会在运行时通过 propTypes 产生警告消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46997507/