这更多是一个好奇心问题,我认为知道为什么会很有用,但是任何人都可以解释为什么console.log(recipe)打印两次。当我单击“搜索”按钮时,结果在控制台中打印两次。我认为我必须与两次重新渲染组件有关,这可以详细解释。
function Search(props) {
const recipe = useSelector(state => state.recipe)
const dispatch = useDispatch()
const [query, setQuery] = useState("")
console.log(recipe)
const handleQuery = (event) => {
event.preventDefault();
console.log(`Query: ${query}`)
dispatch(fetchRequest(query))
}
return (
<form className={classes.Search} onSubmit={handleQuery}>
<input
className={classes.Search__field}
placeholder="Search over 1,000,000 recipes..."
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<button className={[buttonClasses.Btn, "search__btn"].join(' ')} type="submit"
>
<svg className={"search__icon"}>
<use href={magnifyingGlass + "#icon-magnifying-glass"}></use>
</svg>
<span>Search</span>
</button>
</form>
);
}
export default Search;
在这里使用搜索组件
import React from 'react';
import Search from './Search/Search';
import classes from './Header.module.css';
import logo from '../../img/logo.png';
import Likes from '../Header/Likes/Likes';
const header = (props) => {
return (
<header className={classes.Header}>
<img src={logo} alt="Logo" className={classes.Header__logo} />
<Search />
<Likes />
</header>
)
}
export default header;
然后在Layout函数中使用Header函数 在App.js中
import React, { Component } from 'react';
import Aux from '../../hoc/Aux';
import classes from './Layout.module.css';
import Header from '../Header/Header';
import Results from '../Results/Results';
class Layout extends Component {
render() {
return (
<Aux>
<Header />
<Results />
</Aux>
);
}
}
export default Layout;
这是redux动作
import axios from 'axios';
const FETCH_REQUEST = 'FETCH_USERS_REQUEST'
export const fetchRecipe = (recipe) => {
return {
type: FETCH_REQUEST,
payload: recipe
}
}
export const fetchRequest = (query) => {
console.log(query)
return (dispatch) => {
axios(`https://forkify-api.herokuapp.com/api/search?q=${query}`)
.then(response => {
// console.log(response.data.recipes)
const recipe = response.data.recipes;
dispatch(fetchRecipe(recipe));
})
.catch(error => {
console.log(error)
})
}
}
答案 0 :(得分:1)
Ciao,我不是反应的专家,但您可以进行测试。您知道每次重新渲染组件时都会触发useEffect
挂钩。因此,您可以将console.log放入useEffect中,看看是否将记录两次。像这样:
useEffect(() => {
console.log(recipe);
})
如果您有2条日志,则表示Search
组件被渲染了两次。否则可能与reactjs工作流程有关,而且正如我说的,我不太会解释为什么两次登录。