ReactのWarningをなんとかしたいっ!
2019年2月15日
Warningが気になったので修正していきます。
Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
親切なのか不親切なのか長々としたメッセージですが、要は「Input elements should not switch from controlled to uncontrolled (or vice versa). 」ですね。
controlledからuncontrolledになった(もしくは逆)
場所的には、この辺りで発生しているようで、
<input
name="comment"
type="text"
value={this.state.comment}
/>
コードを追いかけた結果、このthis.state.commentがundefinedになってた
問題はstate側じゃなくて、value={undefined}になるからなのかな?
<input
name="comment"
type="text"
value={this.state.comment || ''}
/>
Warning: Failed prop type: Invalid prop `children` of type `string` supplied to `XXXXXXX`, expected a single ReactElement.
PropTypesのルールがミスってるようなので修正
import propTypes from 'prop-types';
class User extends React.Component {
render() {
return(
<p>ああああ</p>
);
}
}
User.propTypes = {
children: propTypes.element
};
呼び出し元を確認
import User from './user';
class List extends React.Component {
render() {
return(
<User>ああああ</User>
);
}
}
childrenがstringなので、stringに修正。
User.propTypes = {
children: propTypes.string
};
Warning: Each child in a list should have a unique “key” prop.
リストにユニークkeyが無いってやつです
let lists = [];
for (let i = 1; i <= 12; i++) {
lists.push(
<li>
{i}月
</li>
);
}
このliにkeyを追加
let lists = [];
for (let i = 1; i <= 12; i++) {
lists.push(
<li key={i}>
{i}月
</li>
);
}