简体   繁体   English

使用componentWillReceiveProps重新渲染组件?

[英]Re-render component with componentWillReceiveProps?

I have a .jsx with a parent class and a child, in the parent i initialize the api and stock the json content in a state: 我有一个带有父类和子类的.jsx,在父类中,我初始化api并以一种状态存储json内容:

constructor(props) {
    super(props);
    this.state = {
        all: '',
    };
}

componentDidMount() {
    this.loadApi();
}

loadApi(){
    this.setState({ all: myApiGet('https://********') });
}

After that i need to get the "url" of the differents pics for show them on the site. 之后,我需要获取不同图片的“ URL”以在网站上显示它们。 But there is the problem, I get the api json when i load the page and i don't success to re-load the function. 但是有一个问题,我在加载页面时得到了api json,但是我没有成功重新加载该函数。

componentWillReceiveProps(nextProps) {
    this.apiGetProductPicture(nextProps.categorie);
}

apiGetProductPicture = (i) => () => {
        // TODO do something with the data
    var stock = this.props.all
        .then(stock => this.setState({ pictures: stock.content.categories[i].background }))

        .catch(error => console.log('home2', error));
}

I try a lot of possibility and check the net but the solution doesn't work for me (or i just doesn't understand them ...) 我尝试了很多可能性并检查了网络,但该解决方案对我不起作用(或者我只是不理解它们...)

Thanks for your time :/ 谢谢你的时间 :/

Full component: 完整组成部分:

class ProductItem extends React.Component {

constructor(props) {
    super(props);
    this.state = {
        pictures: '',
        name: '',
        price: '',
        json: '',
    };
    //this.apiGetProductPicture = this.apiGetProductPicture.bind(this);
}

componentWillReceiveProps(nextProps) {
    this.apiGetProductPicture(nextProps.categorie);
}

apiGetProductPicture = (i) => () => {
        // TODO do something with the data
    var stock = this.props.all
        .then(stock => this.setState({ pictures: stock.content.categories[i].background }))

        .catch(error => console.log('home2', error));
}


render() {
    return (
             ......
           )
          }
}

Error message: 错误信息:

The above error occurred in the component: in ProductItem (created by Home2) in div (created by Home2) in div (created by Home2) in div (created by Home2) in div (created by Home2) in main (created by Home2) in Home2 上面的错误发生在组件中:在div的ProductItem(由Home2创建)中(由Home2创建)在div中(由Home2创建)在div中(由Home2创建)在div中(由Home2创建)在div中(由Home2创建)在main中(由Home2创建)在Home2中

Consider adding an error boundary to your tree to customize error handling behavior. 考虑将错误边界添加到树中以自定义错误处理行为。 You can learn more about error boundaries at https:// fb.me/react-error-boundaries. 您可以在https:// fb.me/react-error-boundaries中了解有关错误边界的更多信息。 react-dom.development.js:9312:5 ReferenceError: props is not defined react-dom.development.js:9312:5 ReferenceError:道具未定义

Ok i think i see some changes to be made in your parent component your setting this.state.all to be a promise (the promise returned from your api call) 好的,我认为我看到在您的父组件中将this.state.all设置为一个承诺(从您的api调用返回的承诺)中进行了一些更改

let's change that to be the actual json from your api call 让我们将其更改为您的api调用中的实际json

Parent component: 父组件:

constructor(props) {
    super(props);
    this.state = {
        all: '',
    };

    this.loadApi = this.loadApi.bind(this);
}

componentDidMount() {
    this.loadApi();
}

loadApi() {
    myApiGet('https://********')
        .then(all => this.setState({ all }));
}

Child Component: 子组件:

class ProductItem extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            pictures: '',
            name: '',
            price: '',
            json: '',
        };
        this.apiGetProductPicture = this.apiGetProductPicture.bind(this);
    }

    ComponetDidMount() {
         apiGetProductPicture(this.props.categorie);
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.categorie !== this.props.categorie)
        {
            this.apiGetProductPicture(nextProps.categorie);
        }
    }

    apiGetProductPicture(categorie) {
        // TODO do something with the data
        if (!this.props.all) return;
        var categories = (((this.props.all || {}).stock || {}).content || {}).categories;

        if (categories.indexOf(categorie) > -1)
        {
            this.setState({ pictures: categories[categorie].background }));
        }

    }

    render() {
        return (
             ......
        );
    }
}

Thanks for your time :/ 谢谢你的时间 :/

no worries :) 别担心 :)

i se you posted "Lost in the javascriptception" this and other questions have provided me with enough info to solve your problem, sorry the stackoverflow community was so mean to you, but not all of us are like that. 我认为您发布了“ Lost in the javascriptception”,此问题和其他问题为我提供了足够的信息来解决您的问题,对不起stackoverflow社区对您如此卑鄙,但并非所有人都这样。

I would recommend in the future you post more info on your questions, like full code (except sensible stuff), not just parts, the codesanbox was the thing that let me test code and see where the problem was. 我建议将来您发布有关问题的更多信息,例如完整代码(明智的东西除外),而不仅仅是部分内容,codesanbox是让我测试代码并查看问题出在哪里的东西。

Also if*** up on some of the previous answer, but to be fair i had very limited info to go along with, and most people answering won't test the code for tipos or stuff 另外,如果***回答了先前的一些答案,但为了公平起见,我所获得的信息非常有限,并且大多数回答的人都不会测试代码的技巧或内容

version One 版本一

import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

class ProductItem extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      pictures: '',
      name: '',
      price: '',
      json: '',
    };

    this.apiGetProductPicture = this.apiGetProductPicture.bind(this);
  }

  componentDidMount() {
    this.apiGetProductPicture(this.props.categorie);
  }

  componentWillReceiveProps(nextProps) {
      this.apiGetProductPicture(nextProps.categorie);
  }

  apiGetProductPicture(categorie) {
    // TODO do something with the data
    var categories = this.props.send;
    categorie = parseInt(categorie, 10);

    if (categorie < categories.length) {
      console.log(categories[categorie].background);
      this.setState({ pictures: categories[categorie].background });
    }

  }

  render() {
    return (
      <div>
        <p>{this.props.name}</p>
        <img src={this.state.pictures} />
      </div>
        );
  }
}


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      all: "",
      categories: []
    };
    this.loadAPI = this.loadAPI.bind(this);
  }

  componentDidMount() {
    this.loadAPI();
  }

  loadAPI() {

    var test = fetch("https:*******")
      .then(test => test.json())
      .then(testJson => {
        //  alert(testJson.content.categories[0].description)
        var obs = testJson.content.categories.slice();

        // alert(testJson);
        this.setState({ categories: obs });
      });
  }

  render() {
    return (
      <div style={styles}>
        <Hello name="CodeSandbox" />
        <h1>Products</h1>
        {this.state.categories.map( (value, i) => {
          return <ProductItem
                key={value.uid}
                send={this.state.categories}
                name={value.description}
                categorie={i} />
        })}
        <h2>Start editing to see some magic happen {"\u2728"}</h2>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

My recommended Version 我推荐的版本

import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";

const styles = {
  fontFamily: "sans-serif",
  textAlign: "center"
};

class ProductItem extends React.Component {
  render() {
    return (
      <div>
        <p>{this.props.name}</p>
        <img src={this.props.picture} />
      </div>
        );
  }
}


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      all: "",
      categories: []
    };
    this.loadAPI = this.loadAPI.bind(this);
  }

  componentDidMount() {
    this.loadAPI();
  }

  loadAPI() {

    var test = fetch("https:*****")
      .then(test => test.json())
      .then(testJson => {
        //  alert(testJson.content.categories[0].description)
        var obs = testJson.content.categories.slice();

        // alert(testJson);
        this.setState({ categories: obs });
      });
  }

  render() {
    return (
      <div style={styles}>
        <Hello name="CodeSandbox" />
        <h1>Products</h1>
        {this.state.categories.map( (value, i) => {
          return <ProductItem
                key={value.uid}
                picture={value.background}
                name={value.description}
                categorie={i} />
        })}
        <h2>Start editing to see some magic happen {"\u2728"}</h2>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Hope this helps you out, don't be so hard on yourself, you know practice makes perfect, also would recommend you follow the react tutorial , to see what react is about, i can seam super hard and weird because it maybe a completely different programming model (it was for me), but when it click it's really cool 希望这对您有所帮助,不要对自己那么费劲,您知道练习会很完美,也建议您按照react教程 ,看看react是关于什么的,我可以缝得很硬很奇怪,因为这可能是完全不同的编程模型(这是给我的),但是单击它确实很酷

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

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