用流星更新渲染并做出反应

时间:2017-07-24 20:36:02

标签: javascript reactjs meteor

我正在学习Meteor,我正在使用它做出反应,我正在尝试做一个草编应用程序,但是当我想渲染一个吸管时我有一个问题

这是我的StrawpollVote视图的组件:

export default class StrawpollVote extends React.Component{
  constructor(props) {
    super(props);
    Tracker.autorun(() => {
      this.strawpoll = Strawpolls.findOne({ "_id": this.props.match.params.id });
      this.render();
    });
  }

  render(){
    if (this.strawpoll) {
      console.log('strawpoll');
      return (
        <p>Strawpoll : {this.strawpoll.title}</p>
      );
    } else {
      return (
        <p>Strawpoll not found</p>
      );
    }
  }
}

我收到了路由的id,我找到了strawpoll的关联,然后我重新运行了render函数,所有这些都在Tracker.autorun中来监听更改,但当我加载页面时它会显示查看Strawpoll not found在我的控制台中我可以看到渲染函数中的strawpoll

仅当我在自动运行功能上使用this.forceUpdate()时才会起作用但这会引发警告,为什么渲染不会更新视图?我错过了什么吗?

1 个答案:

答案 0 :(得分:0)

我已经像这样更新了你的代码。希望这可能有所帮助:

export default class StrawpollVote extends React.Component{
  constructor(props) {
    super(props);

    this.state = {strawpoll: null};
    let context = this;

    Tracker.autorun(() => {
      let tem = Strawpolls.findOne({ "_id": context.props.match.params.id });
      context.setState({strawpoll: tem});
    });
  }

  render(){
    if (this.state.strawpoll) {
      console.log('strawpoll');
      return (
        <p>Strawpoll : {this.state.strawpoll.title}</p>
      );
    } else {
      return (
        <p>Strawpoll not found</p>
      );
    }
  }
}

更改:在您的代码中,您在this块中使用了Traacker,这不是保留strawpoll的实际上下文。我已将strawpoll置于状态,因为状态更新将自动重新呈现组件,无需强制渲染!

相关问题