组件更新后状态消失

时间:2018-09-06 12:06:41

标签: javascript reactjs react-router state

我制作了小投票应用 带有Home组件和New组件 带有问题和投票选项的家庭渲染状态 在“新组件”中,您可以使用“投票”选项进行新的投票。 通过“添加投票”按钮转到新组件后,旧状态消失, 因此,我cad只添加一个投票。 如何保持这种状态消失?

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>

2 个答案:

答案 0 :(得分:1)

一旦卸下组件,React组件就会失去状态。如果要在卸下组件后仍保持状态,请尝试使用Redux

答案 1 :(得分:0)

您可以将组件分为容器(主页)和演示组件(投票列表,新建)。

即Home将保持状态并呈现列表或新组件。因此,您永远不会失去状态。

添加按钮只会更改状态中的kinda标志,根据该标志,您将呈现组件之一。

相关问题