4 回答

TA貢獻1818條經驗 獲得超8個贊
發生這種情況是因為每個 setState 都會觸發一次渲染,然后再次觸發一次 componentDidMount,這基本上會導致無限循環。要停止該循環,您需要設置一些條件,以防止再次渲染,例如
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}

TA貢獻1824條經驗 獲得超6個贊
我遇到了同樣的錯誤。在使用效果方法中,我使用 axios 從后端獲取數據并更新了狀態。但在更新狀態之前,我沒有將 json 數據轉換為狀態的數據類型,這就是導致此錯誤的原因。
錯誤代碼 :
Useeffect(() => {
fetch
.then((res) =>{
setDate(res.data.date)
})
})
正確代碼:
Useeffect(() => {
fetch
.then((res) =>{
setDate(new Date(res.data.date))
})
})

TA貢獻1815條經驗 獲得超6個贊
看來你想在 props 改變時改變狀態來過濾一些產品。我刪除componentDidUpdate代碼并在組件中添加一個方法來進行過濾,然后我將從父組件中調用該方法
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
matchtedProducts: [],
products: [],
}
}
async componentDidMount() {
try {
const products = await getProducts()
this.setState({ products })
} catch(err) {
console.log(err)
}
}
updateMatches = () => {
const productColor = this.props.size.trim().toLowerCase()
const productSize = this.props.color.trim().toLowerCase()
const matches = []
this.state.products.map(product => {
const title = product.title
const titleSpliitet = title.split(',')
let color = titleSpliitet[1].trim().toLowerCase()
let size = titleSpliitet[2].trim().toLowerCase()
if(color == productColor && size == productSize) {
matches.push(product)
}
})
this.setState({matchtedProducts: matches})
}
render() {
return (<div></div>)
}
}
并在父組件中
changeSizeAndColor = () => {
//note that I called updateMatches of MyComponent
this.setState({color : ... , size : ...} , () => this.myComponent.updateMatches());
}
render() {
return <MyComponent ref={ref => this.myComponent = ref} color={...} size={...}/>
}

TA貢獻1821條經驗 獲得超5個贊
我認為你必須傳遞prevProps和/或prevState作為 的參數componentDidUpdate,并且僅當狀態的 prop 或屬性發生更改時才執行代碼,
例子:
componentDidUpdate(prevProps, prevState) {
// if the property count of the state has changed
if (prevState.count !== this.state.count) {
// then do your code
}
}
文檔:https ://en.reactjs.org/docs/react-component.html#componentdidupdate
添加回答
舉報