reactjs - React - 违反不变性 : Maximum update depth exceeded

标签 reactjs react-native react-state-management

我有从另一个类设置我的状态的功能,但我收到以下错误

Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.

这是我的代码

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }

  async componentWillMount() {
    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Ionicons.ttf"),
    });
    this.setState({ loading: false });
  }

  setShowAction = (isShowAction) => {
    console.log(isShowAction)
    this.setState({
      showAction: isShowAction
    })
  }

...

<ChatListScreen onAction={(isShowAction) => this.setShowAction(isShowAction)}/>

...

const ChatListScreen = ({ onAction }) => {

    return (
        <ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
    )
}

...

const ChatList = ({ onAction }) => {
    const [selectMode, setSelectMode] = useState(false)
    const chatListDummy = []
    const [selectedItem, setSelectedItem] = useState([])
    {selectMode ? onAction(true) : onAction(false)}
    return (
        <FlatList
                data= {chatListDummy}
                keyExtractor= {chat => chat.id}
                renderItem= {({item}) => {
                }}/>
    )
}

export default ChatList

有人可以帮忙吗?

最佳答案

查看我的解决方案

const ChatListScreen = ({ onAction }) => {

   return (
       <ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
   )
}
const ChatList = ({ onAction }) => {
   const [selectMode, setSelectMode] = useState(false)
   const [selectedItem, setSelectedItem] = useState([])
   //i dont know where are you using this actally you most use this in a lifesycle or a function
   // {selectMode ? onAction(true) : onAction(false)}
function onClick(){
   selectMode ? onAction(true) : onAction(false)

}
//or a lifecycle
useEffect(()=>{
   selectMode ? onAction(true) : onAction(false)

},[])
return (<div onClick ={onClick} >{"your content"}</div>)

关于reactjs - React - 违反不变性 : Maximum update depth exceeded,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61475043/

相关文章:

reactjs - 无法在 Jenkins 管道中构建 reactjs

react-native - 在按下按钮时重置 StackNavigator React Native

ios - React Native 可以在 Swift 中生成 UIButton 实例吗?

javascript - 当状态改变时 prop 不会更新

reactjs - 没有安装 react-leaflet 库

node.js - 找不到模块 '@babel/core'

javascript - 在嵌套导航器中导航时未定义 route.params?

react-native - 如何在React Native中从输入字段清除焦点?

javascript - 在 React Context 中更新嵌套状态的最佳方法

javascript - 如何在 Hook 中比较来自 react redux 状态的值