React组件出现NaN值及props传递警告的原因排查
问题分析与解决
警告原因
你虽然在构造函数里给super()传了props,但紧接着手动给this.props赋值了新对象{increment: 3},这直接覆盖了React自动为组件实例绑定的props引用。React要求组件props必须由父组件传入或内部默认机制管理,手动赋值this.props会破坏React的props管理逻辑,因此触发警告。
NaN问题原因
渲染<Count />时你没有传入任何props,React管理的原始props是空对象。你手动覆盖this.props的操作无效(React会忽略这种手动赋值),导致setState回调里的props.increment是undefined,state.count + undefined的结果就是NaN。
解决方法
- 移除手动赋值
this.props的代码:绝对不要手动修改this.props,React会自动处理props的传递与绑定。 - 设置默认props值:用React提供的
defaultProps机制来定义默认的increment值,有两种方式:
方式一:类静态属性(ES7+支持)
class Count extends React.Component { static defaultProps = { increment: 3 }; constructor (props) { super(props); this.state = {count: 0}; } // 其余代码不变 }
方式二:类外部定义
class Count extends React.Component { constructor (props) { super(props); this.state = {count: 0}; } // 其余代码不变 } Count.defaultProps = { increment: 3 };
修改后的完整代码
<body> <div id="root"></div> <script type="text/babel"> class Count extends React.Component { static defaultProps = { increment: 3 }; constructor (props) { super(props); this.state = {count: 0}; } increase() { this.setState((state, props) => ({ count: state.count + props.increment })); } componentDidMount() { this.intervalId = setInterval(() => this.increase(), 1000); } componentWillUnmount() { clearInterval(this.intervalId); } render() { return ( <h1>Counting: {this.state.count}</h1> ); } } ReactDOM.render ( <Count />, document.getElementById('root') ); </script> </body>
修改后,React会正确使用默认的increment值,每秒数值增加3,警告和NaN问题都会消失。
内容的提问来源于stack exchange,提问作者Cold
相关产品推荐
相关产品推荐

