简体   繁体   English

如何在 React 功能组件中正确更新 props

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

I'm new to react, wanted to ask if this piece of code is good practice, because I have a feeling I'm doing something wrong but not sure what.我是新手,想问一下这段代码是否是好的做法,因为我觉得我做错了什么,但不确定是什么。

I have a main class component which has an array of packages which consists of width, height etc.我有一个主要的 class 组件,它有一个由宽度、高度等组成的封装阵列。

I'm passing this packages array as props to another functional component where I want to update these values.我将这个包数组作为道具传递给另一个我想更新这些值的功能组件。 Currently my implementation looks like this:目前我的实现如下所示:

<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/>
}

It works correctly, but as I said, I believe that I'm not using the useState with props correctly.它工作正常,但正如我所说,我相信我没有正确使用带有propsuseState Could someone explain what is wrong here?有人可以解释这里有什么问题吗? Because 3 lines of code to update props' state looks strange for me.因为更新 props 的 state 的 3 行代码对我来说看起来很奇怪。

You never directly mutate props like you do here: props.pck.width = widthProperties[0] .你永远不会像这里那样直接改变道具props.pck.width = widthProperties[0]

To have a correct data flow, width and setWidth should be in the parent component and passed down to the children, so that the children can update their width by calling setWidth .为了有正确的数据流, widthsetWidth应该在父组件中并传递给子组件,以便子组件可以通过调用setWidth来更新它们的width

So, since the parent is a class component, you will have something like:因此,由于父组件是 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>
    )
  }
}

And a Card component like:还有一个 Card 组件,例如:

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

It's common to destructure the value and setter function from useState like so:从 useState 解构值和设置器 function 是很常见的,如下所示:

[value, setValue] = useState(initialValue);

From what I gather from your question, the props.pck.width is the initial value of the input, so you may do something like this:根据我从您的问题中收集到的信息, 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/>

You don't use useState like that.您不会那样使用useState useState returns an array of two things: useState返回一个包含两个东西的数组:

  • The variable you are going to use您要使用的变量
  • A function which is used to change that variable用于更改该变量的 function

So in you case it should look like this:因此,在您的情况下,它应该如下所示:

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.

Remember never to change the variable manually.请记住永远不要手动更改变量。 Do it only through the function useState gives you.只能通过 function useState为您提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 React Functional Component props 不更新 - React Functional Component props does not update 功能组件中的构造函数(道具)反应 - constructor(props) in functional component react 功能组件未在反应中接收道具 - Functional Component not receiving props in react 反应:如何访问 class 组件中的功能组件的道具 - React: How can I acces to props of a functional component in a class component 如何在React无状态功能组件中测试道具? - How do I test props in a React stateless functional component? 如何在 React Native 的一个功能组件中一起使用道具和导航 - How to use props and navigation together in one functional component in react native 如何正确使用React.StatelessFunctionalComponent <Props> 在无状态功能组件上? - How to properly use React.StatelessFunctionalComponent<Props> on a stateless functional component? 如何通过 React Navigation 将导航道具传入功能组件屏幕? - How to pass in navigation props into a functional component screen through React Navigation? 如何在 React 功能组件中添加 Redux function 作为带有 Props 的参数 - How to Add Redux function as a Parameter with Props in React Functional Component 如何将对象作为道具传递给 React.js 中的子功能组件? - How to pass an object as props to a child Functional Component in React.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM