为了账号安全,请及时绑定邮箱和手机立即绑定

试图设置字段的值但它不起作用

试图设置字段的值但它不起作用

有只小跳蛙 2021-11-18 16:31:02
这是我的前端我得到的变量的值interestRate,并monthlyPayment从API。我只想在前端设置这些值。这是我的代码:class Display extends Component {componentDidMount() {    this.calculateAPR();  }  componentDidUpdate(prevProps) {      this.calculateAPR();    }  calculateAPR = () => {    let x = JSON.parse(localStorage.getItem('amount'));     a=x[0].amount;      t=x[0].years;    fetch("https://herokuapp.com/interest?amount="+a+"&numMonths="+t)      .then(res => res.json())      .then(        (result) => {          //console.log(result);          interestRate = result.interestRate;          monthlyPayment = result.monthlyPayment.amount;          console.log(interestRate, monthlyPayment);        },      )        this.calculateMonthlyRepayment(monthlyPayment);        this.percentageAPR(interestRate);  };  calculateMonthlyRepayment = (z) => {    return <p>${z}</p>;  };  percentageAPR = (z) => {    return <p>{z * 100}%</p>;  };  render() {    return (      <div className="flex">        <DisplayChild func={this.percentageAPR()} text="interest rate" />        <DisplayChild          func={this.calculateMonthlyRepayment()}          text=" monthly repayment"        />      </div>    );  }}这是我显示这些值的地方,但这些值没有显示:const DisplayChild = ({ func, text }) => {  return (    <span>      {func} <small>{text}</small>    </span>  );};
查看完整描述

1 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

您需要将值存储在状态信息中。实际上,您只是将它们传递给立即返回然后被丢弃的元素的函数。(你也没有fetch正确处理错误。你不是唯一一个,fetchAPI 有一个设计缺陷,鼓励这种脚步,我写在这里。)

更多关于在文档中处理状态的信息

看评论:

class Display extends Component {

  constructor(props) { // *** Constructor with initial state

      super(props);

      this.state = {

        interestRate: 0,  // *** Use appropriate initial values, 0 probably isn't the right choice

        monthlyPayment: 0

      });

  }


  // *** SOMETHING needs to call this function. You might do it from componentDidMount, for instance.

  calculateAPR = () => {

    let x = JSON.parse(localStorage.getItem('amount'));

    a=x[0].amount; 

    t=x[0].years;


    fetch("https://ftl-frontend-test.herokuapp.com/interest?amount="+a+"&numMonths="+t)

      .then(res => {                                   //

        if (!res.ok) {                                 // *** Note the necessary error handling

          throw new Error("HTTP error " + res.status); //

        }                                              //

        return res.json();

      })

      .then(

        (result) => {

          this.setState({

            interestRate: result.interestRate,

            monthlyPayment: result.monthlyPayment.amount

          });

        },

      )

      .catch(err => {

        // *** Handle/display error here

      });

  };


  // *** You can have these as functions if you want, but since they're pure functions

  // it A) Isn't necessary to re-create them for every instance like this, and B) Is

  // entirely possible for them to be `static` (or even outside the component and closed

  // over).

  calculateMonthlyRepayment = (z) => {

    return <p>${z}</p>;

  };


  percentageAPR = (z) => {

    return <p>{z * 100}%</p>;

  };


  render() {

    // *** You may want logic here to render differently when you don't have the data yet

    return (

      <div className="flex">

        <DisplayChild func={this.percentageAPR()} text="interest rate" />

        <DisplayChild

          func={this.calculateMonthlyRepayment()}

          text=" monthly repayment"

        />

      </div>

    );

  }

}


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 175 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信