簡體   English   中英

簡單的 React 組件拋出“遞歸過多”錯誤

[英]Simple React component throwing "too much recursion" error

我在最近的一個問題中遇到了這個准系統 React 組件。 我在玩弄它,並嘗試將一個新項目(一個對象)添加到state中現有對象的數組中。 但它會引發“遞歸過多”錯誤。

我在 React 中查看了其他有類似問題的問題,但我沒有在componentDidMount()調用this.setState() componentDidMount() 我也沒有從它的render()方法渲染相同的組件。 所以,我不確定是什么導致了這個錯誤。

 class App extends React.Component { constructor(props) { super(props); this.state = { Items: [ {w:1, b:8, name: 'banana'}, {w:7, b:3, name:'apple'}, {w:3, b:5, name:'kiwi'}, {w:6, b:3, name:'strawberry'}, {w:5, b:1, name:'orange'}] }; this.addItem = this.addItem.bind(this); //this.handleAdd = this.handleAdd.bind(this); } // handleAdd() { // this.addItem(10, 5, "mangoes"); // } addItem(){ this.setState(prevState => { Items: [...prevState.Items, {w: 20, b: 3, name: "mangoes"}]; }); } render() { return ( <div> <button className="btn btn-default" onClick={this.addItem}>Add</button> <ul> {this.state.Items.map(e => <li key={e.name}>{`${e.name} ${ew}`}</li>)} </ul> </div> ) } } ReactDOM.render(<App/>, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"> </div>

在構造函數中設置的初始項目集在開始時確實呈現,但“添加”按鈕似乎不起作用。

此外,隨着遞歸錯誤,我在測試時遇到了幾次“RegExp too big”。

你的語法不正確。 使用帶有prevState語法的setState時,您需要返回更新后的狀態,並且不應有終止; 在更新程序函數中。

 class App extends React.Component { constructor(props) { super(props); this.state = { Items: [ {w:1, b:8, name: 'banana'}, {w:7, b:3, name:'apple'}, {w:3, b:5, name:'kiwi'}, {w:6, b:3, name:'strawberry'}, {w:5, b:1, name:'orange'}] }; this.addItem = this.addItem.bind(this); //this.handleAdd = this.handleAdd.bind(this); } // handleAdd() { // this.addItem(10, 5, "mangoes"); // } addItem(){ this.setState(prevState => ({ // notice here use return or use wrapping () Items: [...prevState.Items, {w: 20, b: 3, name: "mangoes"}] // <-- not semicolon here })); } render() { return ( <div> <button className="btn btn-default" onClick={this.addItem}>Add</button> <ul> {this.state.Items.map(e => <li key={e.name}>{`${e.name} ${ew}`}</li>)} </ul> </div> ) } } ReactDOM.render(<App/>, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM