ReactJS - 渲染正确组件的问题

ReactJS - issue with rendering the proper component

本文关键字:组件 问题 ReactJS      更新时间:2023-09-26

我正在从服务器中提取一个json响应。json 是一系列文章。根据 article.id 是偶数还是奇数,将其放置在正确的组件中。

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

控制台日志记录显示文章已放入正确的组件中,但在呈现页面时,它会显示

杰森:

[
    {
      "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
    }
]

反应父组件:

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;

我已经为您创建了工作示例,希望对您有所帮助。所以:

简单的 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'));

小提琴

谢谢