簡體   English   中英

如何在 React 功能組件中正確更新 props

[英]How to update props correctly in React functional component

我是新手,想問一下這段代碼是否是好的做法,因為我覺得我做錯了什么,但不確定是什么。

我有一個主要的 class 組件,它有一個由寬度、高度等組成的封裝陣列。

我將這個包數組作為道具傳遞給另一個我想更新這些值的功能組件。 目前我的實現如下所示:

<Card pck={pck} key={pck.packageId}/>



export default function Card(props) {

const widthProperties = useState(0);
props.pck.width = widthProperties[0]
const setWidth = widthProperties[1];

<input type="number" id={props.pck.packageId} className="form-control"
                               value={props.pck.width} 
                               onChange={(e) => setWidth(parseInt(e.target.value))}
                               placeholder="Width" required/>
}

它工作正常,但正如我所說,我相信我沒有正確使用帶有propsuseState 有人可以解釋這里有什么問題嗎? 因為更新 props 的 state 的 3 行代碼對我來說看起來很奇怪。

你永遠不會像這里那樣直接改變道具props.pck.width = widthProperties[0]

為了有正確的數據流, widthsetWidth應該在父組件中並傳遞給子組件,以便子組件可以通過調用setWidth來更新它們的width

因此,由於父組件是 class 組件,您將擁有如下內容:

class CardsList extends Component {
  state = {
    packages: []
  }

  componentDidMount() {
    fetch('api.com/packages')
      .then(response => response.json())
      .then(result => this.setState({ packages: result.items }))
  }

  setWidth = (width, packageId) => {
    this.setState({
      packages: this.state.packages.map(
        pck => pck.packageId === packageId ?  { ...pck, width } : pck
      )
    })
  }

  render() {
    return (
      <div className="cards-list">
        {this.state.packages.map(pck => (
          <Card pck={pck} setWidth={this.setWidth} key={pck.packageId}/>
        ))}
      </div>
    )
  }
}

還有一個 Card 組件,例如:

const Card = ({ pck, setWidth }) => (
  <input value={pck.width} onChange={e => setWidth(e.target.value, pck.packageId)} />
)

從 useState 解構值和設置器 function 是很常見的,如下所示:

[value, setValue] = useState(initialValue);

根據我從您的問題中收集到的信息, props.pck.width 是輸入的初始值,因此您可以執行以下操作:

[width, setWidth] = useState(props.pck.width);

<input type="number" id={props.pck.packageId} className="form-control"
value={width} 
onChange={(e) => setWidth(parseInt(e.target.value))}
placeholder="Width" required/>

您不會那樣使用useState useState返回一個包含兩個東西的數組:

  • 您要使用的變量
  • 用於更改該變量的 function

因此,在您的情況下,它應該如下所示:

const [widthProperties, setWidthProperties] = useState({}); //Here you can either pass an empty object as an initial value or any structutre you would like.

setWidthProperties(props.pck.width); //Or whatever you want to set it to.

請記住永遠不要手動更改變量。 只能通過 function useState為您提供。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM