【问题标题】:React Uncaught (in promise) TypeError: Cannot read property 'hasChildNodes' of nullReact Uncaught (in promise) TypeError: Cannot read property 'hasChildNodes' of null
【发布时间】:2018-01-04 15:06:27
【问题描述】:

当我这样做时,我在我的反应应用程序中收到此错误 Uncaught (in promise) TypeError: Cannot read property 'hasChildNodes' of null -

this.props.history.push('/search');

我正在使用 react 16.2.0react-router-dom 4.2.2

我的路线定义如下 -

           <Switch>
                <Route          exact    path="/login"           component={Login}       />
                <PrivateRoute   exact    path="/"                component={HomePage}    />
                <PrivateRoute   exact    path="/authors"         component={Authors}      />
                <PrivateRoute   exact    path="/books"           component={Books}       />
                <PrivateRoute   exact    path="/bookDetail/:id"  component={BookDetail}  />
                <PrivateRoute   exact    path="/editBook/:id"    component={EditBook}    />
                <PrivateRoute   exact    path="/addBook"         component={AddBook}     />
                <PrivateRoute   exact    path="/search"          component={Search}     />
            </Switch>     

当我在此处收到来自我的 API 的响应时,我的组件在我的句柄提交函数中出现错误 -

handleSubmit(event) {
    event.preventDefault();
    fetch(SEARCH_API_ENDPOINT+this.state.searchTerm, {
        method: 'get',
        headers: headers 
    })
    .then(response => {
        if (response.ok) {
          return response.json();
        } else {
          throw new Error('Something went wrong ...');
        }
    })
    .then(data => {
        console.log(data.docs);
        this.props.history.push('/search');
        //history.push('/authors') ;
        //<Redirect to='/search'/>;
    })
    .catch(error => {
        notify.show('Something is wrong with something!','error');
        this.setState({ error:error, isLoading: false })
    });
}

我完全不知道为什么会这样。如果您希望我粘贴更多详细信息,请告诉我。

谢谢

【问题讨论】:

  • 你是如何定义你的路线的?尤其是用于 this.props.history.push('/search'); 的组件。
  • 我已经用我的路线更新了我的问题
  • hm.. 我似乎没有注意到这里有什么奇怪的地方。你能用导致这个错误的那一行粘贴组件的代码吗?
  • 再次更新代码,请看
  • 我搞定了。我遵循了这个stackoverflow.com/questions/45666288/…的指示。

标签: reactjs


【解决方案1】:

当发生以下情况时我会更新状态:

.then(data => {
    console.log(data.docs);
    this.setState(() => ({goodToRedirect: true}));
})

然后在render()中,

if(state.goodToRedirect) {
    return (
        <Redirect to="/authors"/>);
}

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2021-09-20
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多