【问题标题】:React Hooks - update state with new propsReact Hooks - 使用新道具更新状态
【发布时间】:2020-06-19 07:13:29
【问题描述】:

我对 Hooks 的新实现感到非常困惑。 如何为收到的道具设置状态值,甚至在收到道具时不会重新渲染。 (这是我想要的结果)

这是我的代码:(我想将“数量”值设置为 null,除非它被道具接收,无论哪种情况,它都应该处于状态并更改)。

import React from 'react';
import Firebase from 'firebase';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import Box from '@material-ui/core/Box';
import TextField from '@material-ui/core/TextField';

export default function NumberField(props) {
  const handleAmountChange = (targetValue) => {
    Firebase.database().ref('users/'+Firebase.auth().currentUser.uid
    +'/details/'+props.date+'/'+props.values.fieldName).set(targetValue);
    setAmount(targetValue);
  }

  const a = props.details[props.values.fieldName];

  const [amount, setAmount] = React.useState(props.details.Calls);

  const GenerateAmount =({amount: a  }) => {
      const  [amount, setAmount] = React.useState(null);
      React.useEffect(() => {
        setAmount (a)
      },{}) 
  }
  return (
    <Box display="flex" p={1} bgcolor={props.values.bgColor}>
    <Grid container direction="column" alignItems="baselline" spacing={2} xs = {12}> 
      <Box display="flex" p={1} >
      <Grid item xs={12}>
        <Box>
          <Grid container justify="center" > 
            <Button variant="contained" style={buttonStyle} onClick={() => handleAmountChange(props.values.buttons.b1)} >{props.values.buttons.b1}</Button>
            <Button variant="contained" style={buttonStyle}  onClick={() => handleAmountChange(props.values.buttons.b2)} >{props.values.buttons.b2}</Button>
            <Button variant="contained" style={buttonStyle}  onClick={() => handleAmountChange(props.values.buttons.b3)} >{props.values.buttons.b3}</Button>
            </Grid>
        </Box>
      </Grid>
      <Grid item xs={6}>
        <Box position="left" left="50%">
          <TextField id="outlined-number" label={props.values.fieldDescription} type="number" value={amount}
            onChange={(e) => handleAmountChange(e.target.value)} 
            InputLabelProps={{shrink: true,}} variant="outlined" />
          </Box>
      </Grid>
        </Box>
    </Grid>
    </Box>
  );
}

【问题讨论】:

  • 为什么要在另一个函数中调用 useState?阅读钩子的第一条规则:reactjs.org/docs/…

标签: javascript reactjs react-hooks react-state


【解决方案1】:

我完全确定你在问什么,但是你可以使用钩子 useEffect 来监听道具何时发生变化,然后设置状态。

像这样:

const [amount, setAdmount] = useState(null);
    useEffect(() => {
        setAmount(props.amount);
    }, [props.amount]);

【讨论】:

  • 我将依赖props.amountprops 将是每个渲染的新对象引用,因此这与没有依赖项相同。
  • 没错,我的错。我改变了答案。
  • 为什么这不是公认的答案?还有更多吗?
  • 另外,我觉得这里不需要状态。当 state 和 prop 像这样耦合在一起时,通常不需要它们。
  • 谢谢!效果很好! (第一个值是要设置的值,第二个值是触发器?要跟踪的值?我正确吗?)我需要状态才能更改值,它是一个文本框。当它发生变化时,它也会触发一个函数将其写入 Firebase DB。这里的 useEffect 目的是“加载”该值并在之前显示它。
猜你喜欢
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 2019-12-11
  • 2020-12-28
相关资源
最近更新 更多