javascript - 为什么自动绑定(bind)的 Prop 会在运行时通过 propTypes 产生警告消息?

标签 javascript reactjs

上下文:
我写了一个简单的包装器来自动绑定(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 in People, but its value is undefined. in People (at App.js:38) in App (at index.js:7)

Warning: Failed prop type: The prop age is marked as required in People, but its value is undefined. 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/

相关文章:

javascript - 返回字符串的问题

javascript - AdonisJs 中的 not_required_when 验证器

javascript - React.js 中的 props 问题

reactjs - 为什么我的应用程序在 React Dev 中有两个实例。工具?

javascript - 如何在功能组件上编写几个 ReactJS 状态?

django - 启动 django 服务器时,我不断收到 NotImplementedError 错误

javascript - 困难的 css 样式 : button alignment AND changing fieldnames AND dynamic text length

Javascript 类属性返回未定义

javascript - 拖动一个变换元素导致在拖动开始时跳转开始

javascript - 继承 React 组件的正确方式