概要
redux-form の Field
で Warning が表示された。
Warning: Cannot update a component from inside the function body of a different component.
環境
react: 16.13.0
redux-form: 8.3.1
警告が出る例
import React, { Component } from "react";
import { Field, reduxForm } from "redux-form";
class Hoge extends Component {
renderField(field) {
const { input, label, type } = field;
return (
<div>
<input {...input} placeholder={label} type={type} />
</div>
);
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit)}>
<Field
label="Title"
name="title"
type="tetx"
component={this.renderField}
/>
<input type="submit" value="Submit" disabled={false} />
</form>
);
}
}
上記のようなコードで Field
に文字を入力すると、Warning が表示された。
解決方法
React16.13.0
で新しく Warning が追加された。
Warnings for some updates during render
A React component should not cause side effects in other components during rendering.
It is supported to call setState during render, but only for the same component. If you call setState during a render on a different component, you will now see a warning:
Warning: Cannot update a component from inside the function body of a different component.
This warning will help you find application bugs caused by unintentional state changes. In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState call into useEffect.
しかし、 React 16.13.1
で Warning が削除された。
React v16.13.1
Revert warning for cross-component updates that happen inside class render lifecycles (componentWillReceiveProps, shouldComponentUpdate, and so on). (@gaearon in #18330)
Warning を削除するなら、React16.13.1
にする必要がある。
または、React16.13.0
より下げる必要がある。
(もしくは、 redux-form の更新を待つ?)
参考