首页 > 解决方案 > 将有状态组件转换为无状态组件

问题描述

我在 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 元素?

标签: reactjs

解决方案


只需将其作为组件道具传递:

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

推荐阅读