简体   繁体   English

状态更改,但子组件未重新呈现

[英]State changes but child component does not re-render

A function in the parent component is called on change of input text of Head component 更改Head组件的输入文本时,将调用父组件中的功能

the function take data from a JSON file and search for keywords received from Head component 该函数从JSON文件中获取数据并搜索从Head组件接收的关键字

Then it changes the state and passes it to the third component which is NewsList 然后它更改状态并将其传递给NewsList的第三个组件

But the NewsList component does not re-render 但是NewsList组件不会重新呈现

The Goal is to get keyword from Head Component Search the JSON file for the keyword find matched data and set the state to the matched data and pass this state as props to NewsList component and render the NewsList component to show this new data 目标是从Head Component获取关键字。在JSON文件中搜索关键字以找到匹配的数据,并将状态设置为匹配的数据,并将此状态作为props传递给NewsList组件,并渲染NewsList组件以显示此新数据

This is the parent component 这是父组件

import React from 'react';
import ReactDOM from 'react-dom';
import JSON from './db';
import Header from './components/header';
import Newslist from './components/newslist';


class Test extends React.Component{

  state = {
      news: JSON,
      filtered:[]
    }

   getKeyword(event){
    let keyword = event.target.value;
    let filtered = this.state.news.filter((item)=>{
        return item.title.indexOf(keyword) > -1;
    });

    console.log(filtered);
    this.setState({filtered})
    console.log(this.state.filtered);


  }


  render(){
    return (
      <div>
      <Header keyword={this.getKeyword.bind(this)}/>
      <Newslist news={this.state.filtered.length === 0 ? this.state.news : 
       this.state.filtered} />
      </div>
    );
  }
}

let cont = document.getElementById('root');
ReactDOM.render(<Test/>, cont);

Here is the code for 1st child component 这是第一个子组件的代码

import React from 'react';

const Header = (props) =>{

    return(
      <div>
        <h3 className="text-center text-primary">Welcome To News Search</h3>
        <input type="text" onChange={props.keyword} id="ipt" className="form- 
        control" placeholder="Search for Keyword"/>

      </div>
    );

}
export default Header;

Here is the code for 2nd child component 这是第二个子组件的代码

import React from 'react';


export default class Newslist extends React.Component{

  constructor(props){
    super();
    this.items = props.news.map((item)=>{
      return(
        <div key={item.id}>
          <h3>{item.title}</h3>
          <p>{item.feed}</p>
        </div>
      );
    })
  }



  render(){
    return(

      <div className="container">
        <h1>news List</h1>
        {this.items}
      </div>

    );
  }

}

This is the JSON File 这是JSON文件

[
{
    "id": 1,
    "title": "New ES6 upgrade available",
    "feed": "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto"
},
{
    "id": 2,
    "title": "The importance of REACT in the development",
    "feed": "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident"
},
{
    "id": 3,
    "title": "REACT developers going on strike",
    "feed": "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
},
{
    "id": 4,
    "title": "Say something again please",
    "feed": "Ut enim ad minima veniam, quis nostrum exercitationem ullam 
corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis 
autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil 
molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla 
pariatur?"
    }
]

your make a typo, fix your code in Newslist : 您输入错误,请在Newslist修复您的代码:

constructor(props){
    // fix here
    super(props);
    // ...
}

UPDATE: you can update the components render function: 更新:您可以更新组件渲染功能:

render() {
    return <div className="container">
      <h1>news List</h1>{
        this.props.news.map((item) => {
          return (
            <div key={item.id}>
              <h3>{item.title}</h3>
              <p>{item.feed}</p>
            </div>
          );
        })
      }
    </div>
  }
this.items = props.news.map((item)=>{
      return(
        <div key={item.id}>
          <h3>{item.title}</h3>
          <p>{item.feed}</p>
        </div>
      );
    })

There are several ways to do it 有几种方法可以做到这一点

  1. remove the above code from constructor and add props.news.map in render method, it will update the component. constructor删除上述代码,并在render方法中添加props.news.map ,它将更新组件。

  2. set the state of the component from props and update state from componentWillReceiveProps . 从props设置组件的state ,并从componentWillReceiveProps更新state

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM