React & Special Props Warning
React & Special Props Warning
key & ref
demo
index.js:1 Warning: Comment:
key
is not a prop. Trying to access it will result inundefined
being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://fb.me/react-special-props)
in Comment (at comment.jsx:85)
in div (at comment.jsx:83)
in CommentList (at with.jsx:33)
in Unknown (at App.js:43)
in div (at App.js:37)
in App (at src/index.js:9)
in StrictMode (at src/index.js:8)
import React, { Component } from 'react';
class Comment extends Component {
constructor(props) {
super(props);
}
render() {
const {
comment,
id,
key,// ❌ Warning: Comment: `key` is not a prop.
} = this.props;
console.log(`✅ this.props =`, this.props);
console.log(`❌ key =`, key, key === undefined);
return (
<div className="comment-box">
<p>Comment = {comment}</p>
<p>id = {id}</p>
<p>key = {key === undefined ? "undefined" : key}</p>
</div>
)
}
}
class CommentList extends React.Component {
constructor(props) {
super(props);
this.state = {
// "DataSource" is some global data source
// comments: DataSource.getComments(),
comments: [
{
msg: "comment 1",
id: "c1",
},
{
msg: "comment 2",
id: "c2",
},
{
msg: "comment 3",
id: "c3",
},
],
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
// Subscribe to changes
// DataSource.addChangeListener(this.handleChange);
setTimeout(() => {
this.handleChange();
}, 7*1000);
}
componentWillUnmount() {
// Clean up listener
// DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
// Update component state whenever the data source changes
this.setState({
// comments: DataSource.getComments(),
comments: [
{
msg: "new comment 1",
id: "c1",
},
{
msg: "new comment 2",
id: "c2",
},
{
msg: "new comment 3",
id: "c3",
},
],
});
}
render() {
return (
<div>
{this.state.comments.map((comment) => (
<Comment comment={comment.msg} id={comment.id} key={comment.id} />
))}
</div>
);
}
}
export default CommentList;
StrictMode
React render twice bug ❌❓
https://www.cnblogs.com/xgqfrms/p/13732464.html
StrictMode
https://reactjs.org/docs/strict-mode.html
StrictMode 是用于突出显示应用程序中潜在问题的工具。
与Fragment一样,StrictMode不会呈现任何可见的UI。
它为后代激活其他检查和警告。
注意: 严格模式检查仅在开发模式下运行;它们不会影响生产。
import React from 'react';
function ExampleApplication() {
return (
<div>
<Header />
<React.StrictMode>
<div>
<ComponentOne />
<ComponentTwo />
</div>
</React.StrictMode>
<Footer />
</div>
);
}
demos
render twice bug ❌
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
render once OK ✅
ReactDOM.render(
<>
<App />
</>,
document.getElementById('root')
);
refs
https://reactjs.org/warnings/special-props.html
https://reactjs.org/docs/strict-mode.html
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13929495.html
未经授权禁止转载,违者必究!