在呈现其他组件警告时无法更新组件

我在反应中收到此警告:


index.js:1 Warning: Cannot update a component (`ConnectFunction`) 

while rendering a different component (`Register`). To locate the 

bad setState() call inside `Register` 

我转到堆栈跟踪中指示的位置并删除了所有设置状态,但警告仍然存在。这是否可能从 redux 调度中发生?


我的代码:


注册.js


class Register extends Component {

  render() {

    if( this.props.registerStatus === SUCCESS) { 

      // Reset register status to allow return to register page

      this.props.dispatch( resetRegisterStatus())  # THIS IS THE LINE THAT CAUSES THE ERROR ACCORDING TO THE STACK TRACE

      return <Redirect push to = {HOME}/>

    }

    return (

      <div style = {{paddingTop: "180px", background: 'radial-gradient(circle, rgba(106,103,103,1) 0%, rgba(36,36,36,1) 100%)', height: "100vh"}}>

        <RegistrationForm/>

      </div>

    );

  }

}


function mapStateToProps( state ) {

  return {

    registerStatus: state.userReducer.registerStatus

  }

}


export default connect ( mapStateToProps ) ( Register );

函数,它触发我的寄存器窗体组件中由寄存器调用的警告.js


handleSubmit = async () => {

    if( this.isValidForm() ) { 

      const details = {

        "username": this.state.username,

        "password": this.state.password,

        "email": this.state.email,

        "clearance": this.state.clearance

      }

      await this.props.dispatch( register(details) )

      if( this.props.registerStatus !== SUCCESS && this.mounted ) {

        this.setState( {errorMsg: this.props.registerError})

        this.handleShowError()

      }

    }

    else {

      if( this.mounted ) {

        this.setState( {errorMsg: "Error - registration credentials are invalid!"} )

        this.handleShowError()

      }

    }

  }

堆栈跟踪:

http://img.mukewang.com/633568cb0001e0ff03390081.jpg

ITMISS
浏览 1025回答 5
5回答

慕斯709654

此警告是在 React V16.3.0 之后引入的。如果您使用的是功能组件,则可以将 setState 调用包装到使用效果中。不起作用的代码:const HomePage = (props) => {&nbsp; &nbsp;&nbsp;&nbsp; props.setAuthenticated(true);&nbsp; const handleChange = (e) => {&nbsp; &nbsp; props.setSearchTerm(e.target.value.toLowerCase());&nbsp; };&nbsp; return (&nbsp; &nbsp; <div key={props.restInfo.storeId} className="container-fluid">&nbsp; &nbsp; &nbsp; <ProductList searchResults={props.searchResults} />&nbsp; &nbsp; </div>&nbsp; );};现在,您可以将其更改为:const HomePage = (props) => {&nbsp; // trigger on component mount&nbsp; useEffect(() => {&nbsp; &nbsp; props.setAuthenticated(true);&nbsp; }, []);&nbsp; const handleChange = (e) => {&nbsp; &nbsp; props.setSearchTerm(e.target.value.toLowerCase());&nbsp; };&nbsp; return (&nbsp; &nbsp; <div key={props.restInfo.storeId} className="container-fluid">&nbsp; &nbsp; &nbsp; <ProductList searchResults={props.searchResults} />&nbsp; &nbsp; </div>&nbsp; );};

慕尼黑8549860

只是来这里是因为我刚刚遇到了这个问题,在我意识到我做错了什么之前,我花了一点时间去挖掘 - 我只是没有注意我如何编写我的功能组件。我想我会在这里留下一个答案,以防有人来找,他们犯了和我一样简单的错误。我正在这样做:const LiveMatches = (props: LiveMatchesProps) => {&nbsp; const {&nbsp; &nbsp; dateMatches,&nbsp; &nbsp; draftingConfig,&nbsp; &nbsp; sportId,&nbsp; &nbsp; getDateMatches,&nbsp; } = props;&nbsp; if (!dateMatches) {&nbsp; &nbsp; const date = new Date();&nbsp; &nbsp; getDateMatches({ sportId, date });&nbsp; };&nbsp; return (<div>{component stuff here..}</div>);};我只是忘记了使用,然后发送我的 redux 呼叫useEffectgetDateMatches()太愚蠢了,我在所有其他组件中都一直在做的事情,哈哈。所以它应该是:const LiveMatches = (props: LiveMatchesProps) => {&nbsp; const {&nbsp; &nbsp; dateMatches,&nbsp; &nbsp; draftingConfig,&nbsp; &nbsp; sportId,&nbsp; &nbsp; getDateMatches,&nbsp; } = props;&nbsp; useEffect(() => {&nbsp; &nbsp; if (!dateMatches) {&nbsp; &nbsp; &nbsp; const date = new Date();&nbsp; &nbsp; &nbsp; getDateMatches({ sportId, date });&nbsp; &nbsp; }&nbsp; }, [dateMatches, getDateMatches, sportId]);&nbsp; return (<div>{component stuff here..}</div>);};简单而愚蠢的错误,但花了一段时间才意识到这一点,所以希望这有助于其他人解决这个问题。

慕哥6287543

请仔细阅读错误消息,我的指向具有错误设置状态的登录组件。当我检查时,我有一个不是Arrow函数的onpress。就像这样:onPress={navigation.navigate("Home",&nbsp;{&nbsp;screen:&nbsp;"HomeScreen"&nbsp;})}我把它改成了这样:onPress={()&nbsp;=>&nbsp;navigation.navigate("Home",&nbsp;{&nbsp;screen:&nbsp;"HomeScreen"&nbsp;})&nbsp;}我的错误消息是:警告:在呈现其他组件 () 时无法更新组件 ()。若要在 内部找到错误的 setState() 调用,请按照登录(在登录屏幕.tsx:20)中的&nbsp;https://reactjs.org/link/setstate-in-render&nbsp;中所述的堆栈跟踪进行操作。ForwardRef(BaseNavigationContainer)SignInSignIn

慕娘9325324

我通过将调度从寄存器组件呈现方法删除到组件卸载方法来解决此问题。这是因为我希望在重定向到登录页面之前发生此逻辑。一般来说,最好的做法是将所有逻辑放在渲染方法之外,这样我的代码以前写得很糟糕。希望这对将来的其他人有所帮助:)我重构的寄存器组件:class Register extends Component {&nbsp; componentWillUnmount() {&nbsp; &nbsp; // Reset register status to allow return to register page&nbsp; &nbsp; if ( this.props.registerStatus !== "" ) this.props.dispatch( resetRegisterStatus() )&nbsp; }&nbsp; render() {&nbsp; &nbsp; if( this.props.registerStatus === SUCCESS ) {&nbsp;&nbsp; &nbsp; &nbsp; return <Redirect push to = {LOGIN}/>&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div style = {{paddingTop: "180px", background: 'radial-gradient(circle, rgba(106,103,103,1) 0%, rgba(36,36,36,1) 100%)', height: "100vh"}}>&nbsp; &nbsp; &nbsp; &nbsp; <RegistrationForm/>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}

天涯尽头无女友

如果使用效果无法在您的案例中使用,或者错误不是由于 Redux我曾经将两个变量中的一个重定向到回调队列。setTimeoutuseState我有一个父组件和一个子组件,每个组件中都有变量。解决方案是使用 包装变量:useStateuseStatesetTimeoutsetTimeout(() => SetFilterData(data), 0);以下示例父组件import ExpenseFilter from '../ExpensesFilter'&nbsp; &nbsp;&nbsp;function ExpensesView(props) {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const [filterData, SetFilterData] = useState('')&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const GetFilterData = (data) => {&nbsp; &nbsp; &nbsp; &nbsp;// SetFilterData(data);&nbsp; &nbsp; &nbsp; &nbsp;//*****WRAP useState VARIABLE INSIDE setTimeout WITH 0 TIME AS BELOW.*****&nbsp; &nbsp; &nbsp; &nbsp;setTimeout(() => SetFilterData(data), 0);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const filteredArray = props.expense.filter(expenseFiltered =>&nbsp;&nbsp; &nbsp; &nbsp; expenseFiltered.dateSpent.getFullYear().toString() === filterData);&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return (&nbsp; &nbsp; <Window>&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <ExpenseFilter FilterYear = {GetFilterData}></ExpenseFilter>子组件const ExpensesFilter = (props) => {&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const [filterYear, SetFilterYear] = useState('2022')&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; const FilterYearListener = (event) => {&nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault()&nbsp; &nbsp; &nbsp; &nbsp; SetFilterYear(event.target.value)&nbsp; &nbsp; }&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; props.FilterYear(filterYear)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return (
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript