gpt4 book ai didi

javascript - 在不扩展组件的类中更新 React 中的变量

转载 作者:行者123 更新时间:2023-12-01 02:25:40 25 4
gpt4 key购买 nike

我正在尝试围绕 ReactJS 进行思考,但我被一个问题所困扰,我希望能够更新局部变量的值并返回更新后的值。

我读过有关状态的内容,并且在使用 React Components 时使用过它,但是,此类仅定义为 const 并且它不扩展 React.Component。

我应该有不同的方式来定义设置变量吗?

这是我的代码的简化版本:

import React from 'react';

const WelcomeForm = ({welcome}) => {

var welcomeMsg = 'Test';

DynamicContentApi.loadDynamicContent('welcome_test').then((response) => {
// response.text has content
welcomeMsg = response.text;
}).catch(() => {
welcomeMsg = '';
});

return (
<p>{welcomeMsg}</p> // Returns 'Test'
);
};

export default WelcomeForm;

最佳答案

这里最简单的选择是将无状态组件更改为有状态组件

Stateless components are just JavaScript functions. They take in an optional input, called prop.

Stateful components offer more features, and with more features comes more baggage. The primary reason to choose class components (stateful) over functional components (stateless) is that they can have state, that is what you want to update to re-render.

您可以执行以下操作:

class WelcomeForm extends React.Component {
state = {
welcomeMsg: ''
}
fetchFromApi() {
DynamicContentApi.loadDynamicContent("welcome_test")
.then(response => {
this.setState({welcomeMsg: response.text});
})
.catch((e) => console.log(e));
}
componentDidMount() {
fetchFromApi();
}
render() {
return (
<p>{welcomeMsg}</p>
);
}
};

如果您出于任何原因想要使组件保持无状态,则必须将 loadDynamicContent() 函数放在父级上,并将文本传递给 WelcomeForm 作为 Prop 。例如:

// Your WelcomeForm Component
const WelcomeForm = ({welcomeMsg}) => (
<p>{welcomeMsg}</p>
);

// Whatever it's Parent Component is
class Parent extends React.Component {
state = {
welcomeMsg: ''
}
fetchFromApi() {
DynamicContentApi.loadDynamicContent("welcome_test")
.then(response => {
// response.text has content
this.setState({welcomeMsg: response.text});
})
.catch((e) => console.log(e));
}
componentDidMount() {
fetchFromApi();
}
render() {
<WelcomeForm welcomeMsg={this.state.welcomeMsg} />
}
}

关于javascript - 在不扩展组件的类中更新 React 中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48833967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com