2021年3月3日星期三

Can not set state by function is rendered by function in reactJS

Im try make a sidebar menu without lib and i got a problem.

I have a function use for setState , but it only work with JSX in return, when i render menu and pass this function, it is run but setState not working in it.

Hear is my code:

export default function DropdownSideMenu(props) {      const [state, setState] = useState({});        const renderDropdownMenu = (data) => {          return data.map((item) => {              if (item.child.length >= 1) {                  return (                      //THIS IS NOT WORKING, doSomeThing run but state not change.                      <li key={item.id} onClick={() => doSomeThing(item.value)}>                          <NavLink to={item.link}>{v[item.name]}</NavLink>                          <ul>{renderDropdownMenu(item.child)}</ul>                      </li>                  );              }                return (                  <li key={item.id}>                      <NavLink to={item.link}>{v[item.name]}</NavLink>                  </li>              );          });      };        const doSomeThing = (value) => {          console.log(value);          setState(value);      };        return (          <ul>              {renderDropdownMenu(props.data)}                {/* THIS IS WORKING, doSomeThing run well */}              <li onClick={() => doSomeThing(value)}>                  <NavLink to="/">Test</NavLink>              </li>          </ul>      );  }  

UPDATE: Problem-solve I found a big mistake in project, when project building, I make Layout component and PUT IT INTO CONTAINER COMPONENT, this is wrong way because when we triggle Sidebar in Layout component Router will re-render container and make Layout re-render so Sidebar can not make action setState.

I FIXED BY PUT LAYOUT INTO APP COMPONENT and WRAP ALL CONTAINER INSIDE LAYOUT COMPONENT, it work fine.

P/s: If someone see another mistake, pls comment. Thanks you so much

https://stackoverflow.com/questions/66453865/can-not-set-state-by-function-is-rendered-by-function-in-reactjs March 03, 2021 at 05:06PM

没有评论:

发表评论