簡體   English   中英

組件更新后狀態消失

[英]State disappear after Component Update

我用Home組件和New組件制作了小的Poll App,其中New Component中的問題和投票選項帶有Home Render狀態。您可以使用表決選項進行新的投票。 通過“添加投票”按鈕轉到“新組件”后,舊狀態消失,因此我只能添加一個“投票”。 如何保持這種狀態消失?

 import React, {Component} from 'react'; import {Link} from 'react-router-dom'; import Poll from './Poll' class Home extends Component { state = { question:"", tag:[], } componentDidMount() { if (this.props.location.state !== undefined) { const tag = this.props.location.state.tag; const que= this.props.location.state.question; this.setState({ tag: [...this.state.tag, tag], question: [...this.state.question, que] }) } } render() { return ( <div style={{marginTop:"200px", width:"1200px", marginLeft:"auto", marginRight:"auto"}}> <ul style= {{display:"flex",justifyContent:"center",alignItems:"center"}}> <Poll question={this.state.question} tag={this.state.tag} /> </ul> <div style={{marginTop:"30px"}} > <Link to='/New'> <button style={{width:"100px", height:"80px", cursor:"pointer" }}> Add Poll </button> </Link> </div> </div> ) }; } export default Home; 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

編輯:

我通過新組件傳遞狀態

 <Link to={this.state.question && this.state.tag[0] ? { pathname: '/', state: { question: this.state.question, tag : this.state.tag } } : { pathname: '/New'}}> <button style={{padding:"8px", marginTop:"10px"}}> Add new poll </button> </Link> 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 

 <BrowserRouter> <Switch> <Route exact path ="/" component={Home}/> <Route path ="/New" component={New} /> </Switch> </BrowserRouter> 

一旦組件卸下,React組件就會失去狀態。 如果要在卸下組件后仍保持狀態,請嘗試使用Redux

您可以將組件分為容器(主頁)和演示組件(投票列表,新建)。

即Home將保持狀態並呈現列表或新組件。 因此,您永遠不會失去狀態。

添加按鈕只會更改狀態中的kinda標志,根據該標志,您將呈現組件之一。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM