在上级父组件中更新子状态

时间:2019-04-15 07:54:42

标签: reactjs

我需要一些帮助。我有一个包装器<style> body { background-image: url(https://i.imgur.com/<?php echo $_GET['img']; ?>.jpg); } </style> 组件,用于保存应用程序的状态,App组件呈现一个App组件。我需要在应用程序的每个页面中设置页面上所做的更改。每个页面都有一个使用Router的下一页按钮。

我尝试传递句柄更改方法,但无法使其正常工作,NavLink未被解雇。任何帮助将不胜感激。

应用程序:

handleChange

路由器:

export default class App extends React.Component {
  state = {
    categoriesWithSub: [],
    currentPage: '',
    ticket: {
      departments: '',
      request: '',
      exactRequest: '',
      attachments: '',
    },
  };

  componentDidMount = async () => {
    const categories = await getCategories();

    const categoriesWithSub = await Promise.all(
      categories.map(async category => {
        const subCategories = await getSubCategories(category.id);
        return { ...category, subCategories };
      }),
    );
    this.setState({ categoriesWithSub });
  };

  makeHandleChange = () => {
    alert('Test!');
    /* this.setState({
      ticket: { ...this.state.ticket, [pageName]: pageChanges },
    }); */
  };

  render() {
    const { categoriesWithSub } = this.state;

    return <Router categoriesWithSub={categoriesWithSub} handleChange={this.makeHandleChange} />;
  }
}

子组件:

const routes = [
  {
    path: '/',
    exact: true,
    component: Home,
  },
  {
    path: '/departments',
    exact: true,
    component: Departments,
  },
  {
    path: '/request',
    exact: true,
    component: Request,
  },
  {
    path: '/thank-you',
    exact: true,
    component: ThankYou,
  },
  {
    path: '/success',
    exact: true,
    component: Success,
  },
];

export default function Router(categoriesWithSub, handleChange) {
  return (
    <Switch>
      {routes.map(({ path, exact, component: Component, layoutProps = {} }) => {
        const WithLayout = ({ ...props }) => (
          <Layout {...layoutProps}>
            <Component {...props} />
          </Layout>
        );
        return (
          <Route
            key={path}
            path={path}
            exact={exact}
            render={() => <WithLayout categoriesWithSub={categoriesWithSub} handleChange={handleChange} />}
          />
        );
      })}
    </Switch>
  );
}

1 个答案:

答案 0 :(得分:1)

这不起作用

C

应该是

export default function Router(categoriesWithSub, handleChange)