2017-09-25 95 views
-1

我想在用戶在我的應用程序中創建任務時顯示一條信息性消息。我已經在一段時間內做出了反應,但我無法想象在顯示一次後顯示消失的消息的邏輯。如何構建反應應用程序以正確渲染組件?

這裏的當前設置

App.js它採用反應DOM路由器路由到不同的頁面,看起來像 主要成份:

class App extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     taskCreated: false, 
    }; 
    } 

    showTaskCreatedAlert =() => { 
    this.setState({ taskCreated: true }); 
    }; 

    render() { 
    return (
     <Router> 
      <div> 
      <Switch> 
       <Route 
       exact 
       path="/" 
       component={props => <TasksIndex {...this.state} />} 
       /> 
       <Route 
       path="https://stackoverflow.com/users/new" 
       component={props => (
        <TasksNew 
        showTaskCreatedAlert={this.showUserCreatedAlert} 
        {...props} 
        /> 
       )} 
       /> 
      </Switch> 
      </div> 
     </Router> 
    ); 
    } 
} 

TasksNew.js 組件呈現用戶可以創建任務的表單

當任務成功創建時,我upd吃我的父組件上的狀態(App.js並將taskCreated設置爲true。然後我將歷史記錄推送到根資源「/」。

TasksIndex.js 組件呈現用戶 此組件獲得的主要部件的狀態傳遞給它的道具並根據taskCreated是否設置爲true或false,它會顯示信息創建的所有任務消息

一切都很好,除了該消息在用戶導航到/ users/new並返回後不會消失。只有完全重新加載纔會消失。現在我知道爲什麼會發生這種情況:父組件的狀態永遠不會更新,並且taskCreated保持爲真。

但是如何實現這個呢?一旦用戶導航到應用程序中的其他頁面,我如何才能讓消息消失。我想在不使用redux的情況下完成此任務。

+0

我認爲這個鏈接可以幫助您解決問題。 [如何將變量傳遞給父組件](https://stackoverflow.com/questions/38394015/how-to-pass-data-from-child-component-to-its-parent-in-reactjs) – Mukundhan

+0

首先,使用Route的「渲染」道具而不是「組件」。其次,我想知道是否可以使用TasksIndex的componentWillUnmount將taskCreated設置回false? –

回答

0

您需要的僅僅是在任何應用程序路由更改後,將父組件的狀態taskChreated更改爲false。您可以通過訂閱瀏覽器歷史記錄來完成:

import createBrowserHistory from 'history/createBrowserHistory' 

const history = createBrowserHistory() 

class App { 
    constructor(props) { 
     super(props); 
     this.state = { 
      taskCreated: false, 
     }; 
    } 

    showTaskCreatedAlert =() => { 
     this.setState({ taskCreated: true }); 
    }; 

    componentDidMount() { 
     // listen for changes of location 
     this.unlisten = history.listen((location, action) => { 
       this.setState({ taskCreated: false }); 
     }); 
    } 
    componentWillUnmount() { 
     // Remove your listener when your component is destroyed 
     this.unlisten(); 
    } 
    render() { 
     <Router history={history}> 
      // ... 
     </Router> 
    } 
} 
+0

我的應用程序組件從不卸載。只有內部組件安裝/卸載。你也不應該在componentWillUnmount中調用setState。 –

+0

儘管您的應用程序還沒有此用例,但在卸載組件時,最好移除任何偵聽器。 「history.listen」調用將返回一個取消訂閱功能並將其設置爲this.unlisten屬性。稍後,在卸載組件「this.unlisten()」將刪除一個歷史偵聽器,並且它不會調用setState。 –