reactjs - 将有状态组件转换为无状态组件
问题描述
我在 React 中有这个工作状态组件:
import React, {Component} from "react";
class MyComponent extends Component {
constructor() {
super();
this.myRef = React.createRef();
this.state = {
array: [],
noresults: false
};
}
loadData = () => {
let data = this.myRef.current.value;
let url = "someurl="+data;
if(!data) {
return;
}
fetch(url)
.then((res) => res.json())
.then((json) => {
if(json.data.length > 0) {
this.setState({
array: json.data,
noresults: false
});
} else {
this.setState({
noresults: true
});
}
})
}
render() {
const { array, noresults } = this.state;
return (
<div>
<section>
<input ref={this.myRef} type="number"/>
<button onClick={this.loadData}>Click Here</button>
</section>
<ul>
{
array.map((e) => (
<li key = { e.key } >
{ e.data }
</li>
))
}
</ul>
{noresults && <div>No Records</div>}
</div>
);
}
}
export default MyComponent
我想像这样将其转换为无状态:
function MyComponent() {
return (
<div>
<section>
<input type="number"/>
<button>Click Here</button>
</section>
<ul>
<li></li>
</ul>
<div>No Records</div>
</div>
);
}
export default MyComponent
现在如何将输入数据传递给我的方法以进行 API 调用。另外如何传递来自 API 的响应以显示为 ul 和 li 元素?
解决方案
只需将其作为组件道具传递:
const MyComponent = ({array = [], loadData = () => {}}) => {
const [inputValue, setInputValue] = useState();
const handleInputChange = (evt) => {
setInputValue(evt.target.value);
};
return (
<div>
<section>
<input type="number" onChange={handleInputChange} />
<button onClick={e => loadData(e, inputValue)}>Click Here</button>
</section>
<ul>
{array.map((e) => (<li key={e.key}>{e.data}</li>))}
</ul>
{array.length === 0 && <div>No Records</div>}
</div>
);
}
对于输入,我创建了一个本地状态,该状态在输入更改时更新并将其传递给loadData
函数。您可以通过参数化函数访问当前值loadData
:
loadData = (e, currentInputValue) => { ... };
推荐阅读
- linux - 定义环境变量引用容器的变量环境 [kubernetes]
- c - 在后面插入节点时出现 LinkedList 分段错误
- elasticsearch - 为什么我的时间戳范围查询没有返回任何内容
- angular - Facebook 提要对话框错误:参数“href”应表示有效的 URL
- javascript - 某些特定数据未从服务器文件保存在数据库中
- python - 升级`pip`会删除其他python的点子
- c++ - 错误:AddressSanitizer:负大小参数:(大小=-1)
- javascript - 在 Typescript 中编写 sanitizer 函数来检查 null、未定义和空字符串并在函数内部出错
- sql - 如何处理 informatica 中的指数值
- git - 更改 git 合并分支冲突消息