ReactJS - 渲染正确组件的问题

时间:2016-02-10 10:48:53

标签: javascript reactjs

我从服务器提取json响应。 json是一系列文章。根据article.id是偶数还是奇数,它被放置在适当的组件中。

如果文章的id是偶数,则将对象放在LeftLargeImageArticle组件中,否则将其放在LargeRightImageArticle组件中。

控制台日志记录显示文章被放入适当的组件中,但是当呈现页面时,它会显示

JSON:

[
    {
      "image": "test1.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 1
    },
{
      "image": "test2.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 2
    },
{
      "image": "test3.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 3
    },
{
      "image": "test4.jpg",
      "h4": "h4 title",
      "h3": "h3 title",
      "p": "foo bar baz.",
      "id": 4
    }
]

React Parent Component:

var React = require('react');
var ScrollWrapper = require('./reusable-tool-components/ScrollWrapper.react');
var LargeLeftImageArticle = require('./reusable-tool-components/LargeLeftImageArticle.react');
var LargeRightImageArticle = require('./reusable-tool-components/LargeRightImageArticle.react');
var GuidingPrinciplesStore = require('./../stores/GuidingPrinciplesStore');


if (process.env.APP_ENV === 'browser') {
    var GuidingPrinciplesArticlesWebUtilsAPI = require('./../../utils/GuidingPrinciplesArticlesWebUtilsAPI');
    var test = GuidingPrinciplesArticlesWebUtilsAPI.initializeArticles();
    console.log("test: ", test);
}

var GuidingPrinciples = React.createClass({

  handleScroll: function(event) {
    console.log("GuidingPrinciples Component handleScroll");
  },

  getInitialState: function() {
    return {
      articles: GuidingPrinciplesStore.getArticles()
    };
  },

  render: function() {
    // I got them, but need to divide them up to place in the specific component
    var articleNodes = this.state.articles.map(function(article){
      if (article.id % 2 === 0) {
        console.log("put in left: ", article.id);
        return (
          <LargeLeftImageArticle h3={article.h3} h4={article.h4} p={article.p} image={article.image} key={article.id} />
        );
      } else {
        console.log("put in right: ", article.id);
        return (
          <LargeRightImageArticle h3={article.h3} h4={article.h4} p={article.p} image={article.image} key={article.id} />
        )
      }
    });
    console.log("articleNodes: ", articleNodes); /* Shows each article object as typeof react.element. */
    return (
      <div>
        <ScrollWrapper>
        <div className="product">
            <section className="container-fluid">
              <img src="images/gator.jpg" className="img-responsive" />
            </section>

            <section className="container">
              /* 
               * Currently on page rendering: article 1 (left large), 1 (right large), 3 (left large), 1 (right large). 
               * I need it to render: article 1 (right large), article 2 (left large), article 3 (right large), article 4 (left large). 
               * Why is this happening? Why don't the articles get rendered in the proper order? Are they being over-written? 
              */
              {articleNodes} 
            </section>
          </div>
        </ScrollWrapper>
      </div>
    )
  }
});

module.exports = GuidingPrinciples;

根据文章ID是否为偶数,应具有相应道具的子组件:

var React = require('react');

var LargeLeftImageArticle = React.createClass({
  render: function() {
    return (
      <article className="row large-left-img-article">
        <div className="col-md-6">
          <img src={"../images/" + this.props.image} alt={this.props.h3} className="img-responsive" />
        </div>
        <div className="col-md-6 content">
          <header>
            <h4>{this.props.h4}</h4>
            <h3>{this.props.h3}</h3>
          </header>
          <p>{this.props.p}</p>
        </div>
      </article>
    );
  }
});

module.exports = LargeLeftImageArticle;

包含奇数ID的文章的子组件:

var React = require('react');

var LargeRightImageArticle = React.createClass({
  render: function() {
    return (
      <article className="row large-right-img-article">
        <div className="col-md-6 content">
          <header>
            <h4>{this.props.h4}</h4>
            <h3>{this.props.h3}</h3>
          </header>
          <p>{this.props.p}</p>
        </div>
        <div className="col-md-6">
          <img src={"../images/" + this.props.image} alt={this.props.h3} className="img-responsive" />
        </div>
      </article>
    );
  }
});

module.exports = LargeRightImageArticle;

1 个答案:

答案 0 :(得分:1)

我为你创造了有用的例子,我希望它会对你有所帮助。所以:

简单css

.left{
  width: 100px;
  height: 100px;
  float: left;
  background: red;
}

.right{
  width: 100px;
  height: 100px;
  float: right;
  background: green;
}

JSX文件

class Left extends React.Component {
  constructor(props){
    super(props)
  }
  render() {
    const items = this.props.left.map((item)=>{
      return <li>{item}</li>
    })
    return <ul className="left">{items}</ul>
  }
}

class Right extends React.Component {
  constructor(props){
    super(props)
  }
  render() {
    const items = this.props.right.map((item)=>{
      return <li>{item}</li>
    })
    return <ul className="right">{items}</ul>
  }
}

class Main extends React.Component {
  constructor(){
    this.state = {
      count : 0,
      rightElements: [],
      leftElements: []
    }

    this.increment = this.increment.bind(this)
  }
  increment(){
    const newCount = this.state.count + 1,
                right = this.state.rightElements,
                left = this.state.leftElements;
    newCount % 2 === 0 ? right.push(newCount) : left.push(newCount)

    this.setState({
      count: newCount,
      rightElements: right,
      leftElements: left,
    });
  }
  render() {    
    return <div>
      <Right right={this.state.rightElements}/>
      <Left left={this.state.leftElements}/>
      <button onClick={this.increment}>Click Me</button>
    </div>
    }
 }


React.render(<Main/>, document.getElementById('container'));

Fiddle

由于