通过渲染函数更新父组件状态的问题

时间:2019-04-22 11:39:38

标签: javascript reactjs

父APP.js:

import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Header from './components/header';
import Cards from './components/cards';
import Footer from './components/footer';
class App extends Component {
  state = {
    to_favorite: [],
  };


  toFav = data => {
    this.setState(function(prevState, props) {
      if (prevState.to_favorite !== data) {
      if (prevState.to_favorite.includes(data) === false) {
        return {to_favorite: data};
      }
      }
    });
  };


  render() {
    return (
      <React.Fragment>
        <Header data={this.state.to_favorite} />
        <div className="cards-body">
          <Cards toFav={this.toFav} />
        </div>
        <Footer />
      </React.Fragment>
    );
  }
}

函数触发的子组件:

import React, {Component} from 'react';
import Card from './card';

class Cards extends Component {
  state = {
    books: [
      {
        id: '1',
        title: 'HTTP: The Definitive Guide',
        author: 'David Gourley',
        cover: 'http',
        price: '46,61',
      },
      {
        id: '2',
        title: 'JavaScript: The Definitive Guide',
        author: 'David Flanagan',
        cover: 'js',
        price: '35,52',
      },
      {
        id: '3',
        title:
          'The TCP/IP Guide: A Comprehensive, Illustrated Internet Protocols Reference',
        author: 'Charles M.Kozierok',
        cover: 'tcp_ip',
        price: '54,50',
      },
      {
        id: '4',
        title:
          'Node.js 8 the Right Way: Practical, Server-Side JavaSCript The Scales',
        author: 'Jim Wilson',
        cover: 'nodejs',
        price: '28,21',
      },
    ],
    favorite: [],
    bag: [],
  };

  isaFav = data => {
    if (typeof data === 'object') {
      this.setState({favorite: [...this.state.favorite, data]});
    } else {
      this.setState({
        favorite: this.state.favorite.filter(fav => fav.id != data[0]),
      });
    }
  };
  render() {
    return (
      <div className="cards" tofav={this.props.toFav(this.state.favorite)}>
        {this.state.books.map(book => (
          <Card isaFav={this.isaFav} bookInfos={book} />
        ))}
      </div>
    );
  }
}

export default Cards;

我试图在同级组件之间移动数据,而不必通过仅具有切换功能的Redux来从子组件(卡)中获取数据。在这一点上,一切都很酷,我可以为数据做console.log,它显示得很好。当我尝试将状态设置为包含切换功能的父组件时,问题就来了,该函数被触发了很多次。最后,它显示了此错误。

“ react-dom.development.js:55未捕获的恒定违规:超过最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。” / p>

我尝试了componenDidUpdate(),但无法阻止该函数的触发。

有什么解决办法吗?是在反应中使用状态的合适方法吗?

0 个答案:

没有答案