如果我使用索引作为键,我不能让它无法正常工作。唯一的方法是如果我改变数组并使用索引作为键。但是由于文档说不要改变状态(数组),所以如果是这样的话,我不能让它不能很好地工作,这与文档所说的相反。我怎样才能证明它可能会破裂?
function App() {
const [arr, setArr] = React.useState(["A","B","C"]);
function toggleSortOrder() {
let newArr = [...arr];
newArr.reverse();
console.log(JSON.stringify(newArr));
setArr(newArr);
}
return (
<div>
<ul>
{ arr.map((e, i) => <li key={i}>{ e }</li>) }
</ul>
<button onClick={toggleSortOrder} >Toggle Sort Order</button>
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#root"));
<script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
如果我改变状态,我可以让它中断,文档说不应该这样做:
function App() {
const [arr, setArr] = React.useState(["A","B","C"]);
function toggleSortOrder() {
arr.reverse();
console.log(JSON.stringify(arr));
setArr(arr);
}
return (
<div>
<ul>
{ arr.map((e, i) => <li key={i}>{ e }</li>) }
</ul>
<button onClick={toggleSortOrder} >Toggle Sort Order</button>
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#root"));
<script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
但是如果我改变状态并使用索引作为键,我什至不能打破它,如果它是一个类组件:
class App extends React.Component {
state = { arr: ["A","B","C"] };
toggleSortOrder() {
this.state.arr.reverse();
console.log(JSON.stringify(this.state.arr));
this.setState({ arr: this.state.arr });
}
render() {
return (
<div>
<ul>
{ this.state.arr.map((e, i) => <li key={i}>{ e }</li>) }
</ul>
<button onClick={this.toggleSortOrder.bind(this)} >Toggle Sort Order</button>
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector("#root"));
<script src="https://unpkg.com/react@16.12.0/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>