我一直在查看React Hooks函数,并对如何准确使用useState和useEffect重构现有代码有些犹豫。
例如,我有一个像这样的老式组件:
class MyFunction extends React.Component{
state = {
count1: 0,
count2: 0
}
static getDerivedStateFromProps(nextProps, prevState) {
return {count1: nextProps.value1, count2: nextProps.value2}
}
handleChange1 = ({target: {value}}) => {
this.setState({count1: value});
this.props.onCount1Change(value);
}
handleChange2 = ({target: {value}}) => {
this.setState({count2: value});
this.props.onCount2Change(value);
}
componentDidUpdate(){
this.props.someRandomStuffs(this.state.count1, this.state.count2);
}
render(){
return (
<div>
<input type="text" value={this.state.count1} onChange={this.handleChange1} />
<input type="text" value={this.state.count2} onChange={this.handleChange2} />
</div>
)
}
}
现在,我准备了一个解决方案来像这样重构它。
function MyFunction(value1, value2, onCount1Change, onCount2Change, someRandomStuffs){
const [count1, setCount1] = useState(value1);
const [count2, setCount2] = useState(value2);
useEffect(() => someRandomStuffs(count1, count2));
function on1Change ({target: {value}}){
setCount1(value);
onCount1Change(value);
}
function on2Change ({target: {value}}){
setCount2(value);
onCount2Change(value);
}
return(
<div>
<input type="text" value={count1} onChange={on1Change} />
<input type="text" value={count2} onChange={on2Change} />
</div>
);
}
以上重构是否足够接近?我想知道是否可以遵循此方法来重构项目中的其他类。
答案 0 :(得分:0)
您转换后的组件将如下所示。我认为您不需要更多的$existingNames = array("Daniel","Dennis", "Alex");
if (isset($_POST['suggestion']))
{
$name = $_POST['suggestion'];
//$name = "D" ( if i uncomment this it will show Daniel and Denis)
foreach ($existingNames as $exista) {
if(strpos($exista , $name) !== false){
echo $exista;
echo "<br>";
}
}
}
。
getDerivedStateFromProps