S
S
Sergey Alekseev2018-09-26 07:30:59
React
Sergey Alekseev, 2018-09-26 07:30:59

React, how does it work?

How it works ? And why does this code even work? Specifically, about the state of the component.

class News extends React.Component {
    state = {
        filteredNews: this.props.data,
    }
    componentWillReceiveProps(nextProps) {
        console.log({ nextProps })
        console.log({ oldProps: this.props })
    }
    renderNews = () => {
        const { filteredNews } = this.state // используем состояние
        let newsTemplate = null
        if (filteredNews.length) { // везде data заменена на filteredNews
            newsTemplate = filteredNews.map(function(item) {
                return <Article key={item.id} data={item} />
            })
        } else {
            newsTemplate = <p>К сожалению новостей нет</p>
        }
        return newsTemplate
    }
    render() {
        const { filteredNews } = this.state // аналогично, используем состояние
        return (
            <div className="news">
               {this.renderNews()}
               {filteredNews.length ? (
                   <strong className={'news__count'}>
                       Всего новостей: {filteredNews.length}
                   </strong>
               ) : null}
           </div>
       )
    }
}

And this code does not work for me, I took it from the react-course-v2 manual

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-09-26
@serj2000

Recording:

state = {
  filteredNews: this.props.data,
};

similar:
constructor(props) {
    super(props);
    this.state =  {
      filteredNews: this.props.data,
    };
  }

this.props.data is written to state once in the constructor. Subsequently, when a new value of this.props.data is received, the state does not change.
There is no need to define renderNews as an arrow function, it should be converted into a class method.
Before: before : I would make the following changes to renderNews, in addition to remaking it into a class method: 1. early return instead of a variable and an else block, 2. replacing a normal function with an arrow function in the map callback. Result:
renderNews() {
  const { filteredNews } = this.state;

  if (filteredNews.length) {
    return filteredNews.map(item => (
      <Article key={item.id} data={item} />
    ));
  }

  return <p>К сожалению новостей нет</p>;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question