使用componentWillReceiveProps重新渲染组件?

时间:2018-03-19 21:48:39

标签: javascript reactjs

我有一个带有父类和子级的.jsx,在父级中初始化api并将json内容存入状态:

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

componentDidMount() {
    this.loadApi();
}

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

之后我需要得到" url"在网站上显示他们的不同图片。但是有问题,当我加载页面时,我得到了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));
}

我尝试了很多可能性并检查网络,但解决方案对我不起作用(或者我只是不理解它们)。

感谢您的时间:/

完整组件:

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 (
             ......
           )
          }
}

错误讯息:

组件中出现上述错误:     在ProductItem中(由Home2创建)     在div(由Home2创建)     在div(由Home2创建)     在div(由Home2创建)     在div(由Home2创建)     在主(由Home2创建)     在Home2

考虑向树中添加错误边界以自​​定义错误处理行为。 您可以在https:// fb.me/react-error-boundaries中了解有关错误边界的更多信息。 反应-dom.development.js:9312:5 ReferenceError:未定义props

2 个答案:

答案 0 :(得分:0)

好的,我认为我看到了一些变化 在您的父组件中,您将this.state.all设置为一个承诺(从您的api调用返回的承诺)

让我们改变你的api电话中的实际json

父组件:

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

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

componentDidMount() {
    this.loadApi();
}

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

子组件:

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 (
             ......
        );
    }
}
  

感谢您的时间:/

不用担心:)

答案 1 :(得分:0)

我发布了“迷失在javascriptception中” 这个问题和其他问题为我提供了足够的信息来解决你的问题,抱歉stackoverflow社区对你很有意义,但并非所有人都是这样。

我建议将来你发布更多关于你的问题的信息,比如完整的代码(除了明智的东西),而不仅仅是部分,代码框是让我测试代码并查看问题所在的东西。

另外我对之前的一些答案有所了解,但为了公平起见我的信息非常有限,并且大多数人回答都不会测试代码中的提示或内容

第一版

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"));

我推荐的版本

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"));

希望这可以帮助你,不要对自己这么努力,你知道练习做得很完美,也会建议你跟着the react tutorial,看看有什么反应,我可以缝超级硬和怪异因为它可能是一个完全不同的编程模型(它适合我),但当它点击它真的很酷