English 中文(简体)
在发出不同组成部分的警告时,不能更新一个组成部分
原标题:Cannot update a component while rendering a different component warning

我正在对这一警告作出反应:

index.js:1 Warning: Cannot update a component (`ConnectFunction`) 
while rendering a different component (`Register`). To locate the 
bad setState() call inside `Register` 

我前往点击中标出的地点,并拆除了所有固定状态,但警告仍然存在。 能否做到这一点,可能来自红色高棉的派遣?

my code:

登记册。

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 );

function which triggers the warning in my registerForm component called by 登记册。

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()
      }
    }
  }

Stacktrace:

“Stacktrace”/

最佳回答

我将这一问题从登记册各组成部分中删除,从而将方法应用到部件组合方法。 这是因为,在改用原木页之前,我希望这种逻辑会发生。 总的来说,把你的逻辑置于方法之外是最佳的做法,因此,我的法典在前面写得很少。 希望有助于今后其他任何人:

我的登记册组成部分:

class Register extends Component {

  componentWillUnmount() {
    // Reset register status to allow return to register page
    if ( this.props.registerStatus !== "" ) this.props.dispatch( resetRegisterStatus() )
  }

  render() {
    if( this.props.registerStatus === SUCCESS ) { 
      return <Redirect push to = {LOGIN}/>
    }
    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>
    );
  }
}

问题回答

该警告自第V16.3.0号行政指示发布以来即已采用。

如果你使用职能部分,你就可以将既定的国家呼吁总结为效果。

劳动法典:

const HomePage = (props) => {
    
  props.setAuthenticated(true);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

现在,你可以改变这一方向:

const HomePage = (props) => {
  // trigger on component mount
  useEffect(() => {
    props.setAuthenticated(true);
  }, []);

  const handleChange = (e) => {
    props.setSearchTerm(e.target.value.toLowerCase());
  };

  return (
    <div key={props.restInfo.storeId} className="container-fluid">
      <ProductList searchResults={props.searchResults} />
    </div>
  );
};

我刚才有过这个问题,在我弄清我做的错事之前,我只想到我如何撰写我的职能部分。

我正在这样做:

const LiveMatches = (props: LiveMatchesProps) => {
  const {
    dateMatches,
    draftingConfig,
    sportId,
    getDateMatches,
  } = props;

  if (!dateMatches) {
    const date = new Date();
    getDateMatches({ sportId, date });
  };

  return (<div>{component stuff here..}</div>);
};

我刚刚忘记在发出我的红色呼吁之前使用<条码>效应<>代码>。

因此,应当:

const LiveMatches = (props: LiveMatchesProps) => {
  const {
    dateMatches,
    draftingConfig,
    sportId,
    getDateMatches,
  } = props;

  useEffect(() => {
    if (!dateMatches) {
      const date = new Date();
      getDateMatches({ sportId, date });
    }
  }, [dateMatches, getDateMatches, sportId]);

  return (<div>{component stuff here..}</div>);
};

请彻底阅读错误信息。 地雷指有坏的阵亡分子。 I有一张不是Arrow功能的垫子。

情况如下:

onPress={navigation.navigate("Home", { screen: "HomeScreen" })}

我将此改为:

onPress={() => navigation.navigate("Home", { screen: "HomeScreen" }) }

我的错误信息是:

Warning: Cannot update a component (ForwardRef(BaseNavigationContainer)) while rendering a different component (SignIn). To locate the bad setState() call inside SignIn, follow the stack trace as described in https://reactjs.org/link/setstate-in-render in SignIn (at SignInScreen.tsx:20)

I think that this is important. It s from this post that @Red-Baron pointed out:

页: 1 我认为你会再次误解这一信息是警告的。

对父母中最新状况的儿童的回馈没有任何错误。 这始终是罚款。

问题在于一个构成部分在另一个构成部分提出最新情况,而第一个构成部分则在提出。

换言之,没有这样做:

function SomeChildComponent(props) {
    props.updateSomething();
    return <div />
}

但这很不错:

function SomeChildComponent(props) {
    // or make a callback click handler and call it in there
    return <button onClick={props.updateSomething}>Click Me</button>
}

而且,正如丹麦多次指出的那样,在提供同一组成部分的最新信息的同时,也罚款:

function SomeChildComponent(props) {
  const [number, setNumber] = useState(0);

  if(props.someValue > 10 && number < 5) {
    // queue an update while rendering, equivalent to getDerivedStateFromProps
    setNumber(42);
  }

  return <div>{number}</div>
}

http://www.ohchr.org。 不能在你的情况下使用或如果错误为。 注

我使用<条码>准时,将两个<条码>中的一条改为“呼唤”。

我有一个父母和一个子女组成部分,每个部分都有<编码> > 国家变量。 解决办法是<条码> 用户名称<>。 缩略语

setTimeout(() => SetFilterData(data), 0);

www.un.org/Depts/DGACM/index_spanish.htm 例:

<>可见>

import ExpenseFilter from  ../ExpensesFilter 
    
function ExpensesView(props) {
    
    const [filterData, SetFilterData] = useState(  )
    
    const GetFilterData = (data) => {
       // SetFilterData(data);

       //*****WRAP useState VARIABLE INSIDE setTimeout WITH 0 TIME AS BELOW.*****
       setTimeout(() => SetFilterData(data), 0);
    
    }
    
    const filteredArray = props.expense.filter(expenseFiltered => 
      expenseFiltered.dateSpent.getFullYear().toString() === filterData);
    
    
    return (
    <Window>
      <div>
        <ExpenseFilter FilterYear = {GetFilterData}></ExpenseFilter>

http://www.ohchr.org。

const ExpensesFilter = (props) => {
    
    const [filterYear, SetFilterYear] = useState( 2022 )
    
    const FilterYearListener = (event) => {
        event.preventDefault()
        SetFilterYear(event.target.value)
    }
    
    props.FilterYear(filterYear)
    
    return (

Using React and Material UI (MUI) I changed my code from:

<IconButton onClick={setOpenDeleteDialog(false)}>
        <Close />
      </IconButton>

<><>

<IconButton onClick={() => setOpenDeleteDialog(false)}>
        <Close />
      </IconButton>

简单确定

如果您使用<>React Navigation,并且你正在使用setParamssetOptions,你必须将这些内容放在方法componentDidMount( of categorylement/code>或useffects( hook ofFunction elements.

在发出不同组成部分的警告时,不能更新一个组成部分

I have the same problem but when I dispatch an action inside a component rendered. You should dispatch the action inside useEffect hook to fix that problem


//dispatch action to inform user that  Marked days already have hours! 
  React.useEffect(() => {
    if (btn_class ==  redButton ) {
      dispatch({ type: ActionType.ADD_NOTIFICATION, payload:  Marked days already have hours!  });
    } else {
      dispatch({ type: ActionType.ADD_NOTIFICATION, payload:    });
    }
  }, [btn_class, dispatch]);

also use union type for btn-class variable *`

type ButtonState =  btnAddDay  |  redButton  |  btnAddDayBlue  |  btnAddDayGreen ;

页: 1

http://www.ohchr.org。

I was a bit confused as to what exactly triggers the problem, having a minimal immediately runnable example helped me grasp it a little better:

指数.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function NotMain(props) {
  props.setN(1)
  return <div>NotMain</div>
}

function Main(props) {
  const [n, setN] = React.useState(0)
  return <>
    <NotMain setN={setN} />
    <div>Main {n}</div>
  </>
}

ReactDOM.render(
  <Main/>,
  document.getElementById( root )
);
</script>
</body>
</html>

未发现错误:

反应-dom.development.js:61 警告:在提供不同组成部分(“NotMain”)时,无法更新一个部分(“Main”)。 在“NotMain`”内查找坏套线,沿用https://reactjs.org/link/setstate-in-render

之后是 st痕:

    at NotMain (<anonymous>:16:9)
    at Main (<anonymous>:21:31)

假定16:9美元是<代码>props.setN(1)的准确线,但由于Babel JSX译文,线号是缩略号。

如同许多其他答复一样,解决办法是:

function NotMain(props) {
  React.useEffect(() => { props.setN(1) }, [])
  return <div>NotMain</div>
}

我认为,造成这一错误的一般想法是:

你们不应该放弃提供方法,否则,它可能会产生不同的结果,取决于内部如何重新处理导致事情。

在使用功能部件时,这样做的方式是使用hoo。 就我们而言,<条码>效应将在提交后运行,因此,我们从那里做得很出色。

在使用班级时,这一点略为明确,例如:

然而,在使用职能组成部分时,从概念上讲,情况比较好,因为构成部分的职能既是来源,又是规定反馈的守则。

我的案件是使用<条码>,即国名/代码>,而不是<条码>国名/代码>+<条码>。

BAD ❌

  const closePopover = useCallback(
    () =>
      setOpen((prevOpen) => {
        prevOpen && onOpenChange(false);
        return false;
      }),
    [onOpenChange]
  );

<>strong>GOOD <

  const closePopover = useCallback(() => setOpen(false), []);

  useEffect(() => onOpenChange(isOpen), [isOpen, onOpenChange]);

我也面临同样的问题,如果乌木正在做的话,对我来说,这套解决办法是行之有效的。

定型Params/setOptions

在使用效果之外,这个问题正在发生。 因此试图在使用效果中做此类事情。 它的工作如药店

TL;DR; For my case, what I did to fix the warning was to change from useState to useRef

react_devtools_backend.js:2574 Warning: Cannot update a component (`Index`) while rendering a different component (`Router.Consumer`). To locate the bad setState() call inside `Router.Consumer`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
    at Route (http://localhost:3000/main.bundle.js:126692:29)
    at Index (http://localhost:3000/main.bundle.js:144246:25)
    at Switch (http://localhost:3000/main.bundle.js:126894:29)
    at Suspense
    at App
    at AuthProvider (http://localhost:3000/main.bundle.js:144525:23)
    at ErrorBoundary (http://localhost:3000/main.bundle.js:21030:87)
    at Router (http://localhost:3000/main.bundle.js:126327:30)
    at BrowserRouter (http://localhost:3000/main.bundle.js:125948:35)
    at QueryClientProvider (http://localhost:3000/main.bundle.js:124450:21)

关于我所做工作的全面守则(从/ OLD:改为上行)。 然而,this don t matter, Justtries changing from useState to useRef!

import { HOME_PATH, LOGIN_PATH } from  @/constants ;
import { NotFoundComponent } from  @/routes ;
import React from  react ;
import { Redirect, Route, RouteProps } from  react-router-dom ;
import { useAccess } from  @/access ;
import { useAuthContext } from  @/contexts/AuthContext ;
import { AccessLevel } from  @/models ;

type Props = RouteProps & {
  component: Exclude<RouteProps[ component ], undefined>;
  requireAccess: AccessLevel | undefined;
};

export const Index: React.FC<Props> = (props) => {
  const { component: Component, requireAccess, ...rest } = props;

  const { isLoading, isAuth } = useAuthContext();
  const access = useAccess();
  const mounted = React.useRef(false);
  // OLD: const [mounted, setMounted] = React.useState(false);

  return (
    <Route
      {...rest}
      render={(props) => {
        // If in indentifying authentication state as the page initially loads, render a blank page
        if (!mounted.current && isLoading) return null;
        // OLD: if (!mounted && isLoading) return null;

        // 1. Check Authentication is one step
        if (!isAuth && window.location.pathname !== LOGIN_PATH)
          return <Redirect to={LOGIN_PATH} />;
        if (isAuth && window.location.pathname === LOGIN_PATH)
          return <Redirect to={HOME_PATH} />;

        // 2. Authorization is another
        if (requireAccess && !access[requireAccess])
          return <NotFoundComponent />;

        mounted.current = true;
        // OLD: setMounted(true);
        return <Component {...props} />;
      }}
    />
  );
};

export default Index;

我的例子。

具有这一错误的法典:

<Form
    initialValues={{ ...kgFormValues, dataflow: dataflows.length > 0 ? dataflows[0].df_tpl_key : "" }}
    onSubmit={() => {}}
    render={({values, dirtyFields }: any) => {
      
      const kgFormValuesUpdated = {
        proj_key: projectKey,
        name: values.name,
        description: values.description,
        public: values.public,
        dataflow: values.dataflow,
        flavours: flavoursSelected,
        skipOCR: values.skipOCR
      };

      if (!_.isEqual(kgFormValues, kgFormValuesUpdated)) {
        setNewKgFormValues(kgFormValuesUpdated);
      }

劳动法典:

 <Form
    initialValues={{ ...kgFormValues, dataflow: dataflows.length > 0 ? dataflows[0].df_tpl_key : "" }}
    onSubmit={() => {}}
    render={({ values, dirtyFields }: any) => {
      useEffect(() => {
        const kgFormValuesUpdated = {
          proj_key: projectKey,
          name: values.name,
          description: values.description,
          public: values.public,
          dataflow: values.dataflow,
          flavours: flavoursSelected,
          skipOCR: values.skipOCR
        };

        if (!_.isEqual(kgFormValues, kgFormValuesUpdated)) {
          setNewKgFormValues(kgFormValuesUpdated);
        }
      }, [values]);

      return (

我有同样的问题。 我正在确定一些这样的职能:

// my state definition
const [onConfirm, setOnConfirm] = useState<() => void>();

// then I used this piece of code to update the state
function show(onConfirm: () => void) {
    setOnConfirm(onConfirm);
}

问题在于建筑公司。 在React中,固定国家可以承担新的价值,即回报新的价值。 在该案中,React想要让新国家要求获得不正确的赔偿。

changing to this resolved my issue:

setOnConfirm(() => onConfirm);

我面临同样的问题。 这一错误的起因是“使用()”对反应方向的忽略。 我已将它移至“返回”之前,然后将其固定下来。

I don t know what was changed but it worked. If anybody could explain this, I will be glad...

我的旧法典是:


import { Navigate, useLocation } from  react-router-dom ;


export const Navigation = ({ children }: React.PropsWithChildren): JSX.Element => {

    const location = useLocation(); //  ---> Cause of the error

    if (Authenticator.isAuthenticated() && window.sessionStorage.getItem( isAuthenticated ) ===  true ) {
      return <>{children}</>;
    }


    return <Navigate to="/login" state={{ from: location }} replace />;
  };

更正本为:


export const Navigation = ({ children }: React.PropsWithChildren): JSX.Element => {
    if (Authenticator.isAuthenticated() && window.sessionStorage.getItem( isAuthenticated ) ===  true ) {
      return <>{children}</>;
    }

    const location = useLocation(); // moved here and fixed

    return <Navigate to="/login" state={{ from: location }} replace />;
  };

我的错误是:

Warning: Cannot update a component (`Header`) while rendering a different 
component (`Unknown`). To locate the bad setState() call inside `Unknown`, 
follow the stack trace as described in 
https://reactjs.org/link/setstate-in-render
    at http://localhost:3001/static/js/bundle.js:251:5
    at RenderedRoute (http://localhost:3001/static/js/bundle.js:60935:5)
    at Outlet (http://localhost:3001/static/js/bundle.js:61419:26)
    at aside
    at section
    at Drawer

当我 invoking忙地援引一项称为派遣的职能时,我就这样做了。

  const quantityChangeHandler = (direction) => {
    dispatch(cartActions.changeItemQuantity({title, quantityChange: direction}));
  }
...
          <button onClick={() => quantityChangeHandler(-1)}>-</button>
          <button onClick={() => quantityChangeHandler(1)}>+</button>

起初,我直言不.。

我在发言中直接使用<代码>navigate<>/code>时有类似问题。 在我改为“条码”之后,警报即得到解决。

以前

import {useNavigate} from  react-router-dom ;
const navigate = useNavigate();

if (!shouldShow()) {
    navigate("/abc");
    return null;
}

之后

import {Navigate} from  react-router-dom ;

if (!shouldShow()) {
    return <Navigate to="/abc" />
}

Using some of the answers above, i got rid of the error with the following:

from

if (value === "newest") {
  dispatch(sortArticlesNewest());
} else {
  dispatch(sortArticlesOldest());
}

该守则已纳入我的最高级别部分。

<><>>>

    const SelectSorting = () => {
  const dispatch = useAppDispatch();

  const {value, onChange} = useSelect();

  useEffect(() => {
    if (value === "newest") {
      dispatch(sortArticlesNewest());
    } else {
      dispatch(sortArticlesOldest());
    }
  }, [dispatch, value]);




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.