有关如何解决此问题的任何意见...
我在这里的目标是让用户在搜索栏中搜索“简史密斯”,单击搜索按钮并显示包含“简史密斯”的卡片。
当前我拥有的用户正在搜索“简史密斯”(Jane Smith),该名称另存为“术语”,一旦用户单击搜索按钮,“ fetchStudents”功能便会失败,提示它没有“术语” >
我在将'term'的值从SearchBarInput标记传递到SearchBarButton标记时遇到麻烦,因此,在学生容器中,我可以在mapDispatchToProps函数中使用它。
我的searchBar组件由
组成
const SearchBar = ({ onClick, value }) => (
<SearchBarWrapper>
<div>
<FontAwesomeIcon icon="search" className="searchIcon" />
<SearchBarInput
name="searchBarInput"
placeholder=" Search for something..."
label="searchBar"
defaultValue={value}
/>
<SearchBarButton onClick={onClick}>Search</SearchBarButton>
</div>
</SearchBarWrapper>
);
export default SearchBar;
我的学生容器中有
const Students = ({ studentsPayload = [], onClick }) => (
<StudentsContainer>
<SearchBarContainer>
<SearchBar onClick={onClick} />
</SearchBarContainer>
{studentsPayload.length > 0 ? (
<StudentsCard data={studentsPayload} />
) : null}
</StudentsContainer>
);
const mapDispatchToProps = dispatch => ({ onClick: ({ target: { value } }) => dispatch(fetchStudents(value)) });
const mapStateToProps = ({ students: { studentsPayload } }) => ({ studentsPayload });
/**
* Connects component to redux store
*/
const enhancer = connect(
mapStateToProps,
mapDispatchToProps,
)(StudentSearch);
export default enhancer;
我的fetchStudents动作如下
export const fetchStudents = term => async dispatch => {
try {
const { data: { items } } = await fetchData(
`${process.env.REACT_APP_STUDENTS_URLP1}${term}${process.env.REACT_APP_STUDENTS_URLP2}`);
dispatch({ type: FETCH_STUDENTS, studentsPayload: items });
} catch (error) {
throw new Error(error);
}
};
提前谢谢!
答案 0 :(得分:0)
您可以转换Payload
组件以利用SearchBar
挂钩。然后,您可以将useState
处理程序传递给onChange
,该事件处理程序将接收事件并根据SearchInput
更新SearchBar
状态。然后,当您点击Submit时,您可以传递您存储在状态中的输入值。
答案 1 :(得分:0)
谢谢您的帮助!我通过进行以下更改解决了问题:)
在搜索栏组件中
const SearchBar = ({ onClickButton, value, onValueChange }) => (
<SearchBarWrapper>
<div>
<FontAwesomeIcon icon="search" className="searchIcon" />
<SearchBarInput
name="searchBarInput"
label="searchBar"
placeholder="Search for something"
value={value}
onChange={onValueChange}
/>
<SearchBarButton onClick={() => onClickButton(value)}>Search</SearchBarButton>
</div>
</SearchBarWrapper>
);
export default SearchBar;
在“学生”容器中
const Students = ({ studentsPayload = [], onClickButton }) => {
const [value, setValue] = useState('');
const handleChange = ({ target: { value } }) => setValue(value);
return (
<StudentsContainer>
<SearchBarContainer>
<SearchBar
onClickButton={onClickButton}
onValueChange={handleChange}
value={value}
/>
</SearchBarContainer>
{studentsPayload.length > 0 ? (
<StudentsCard data={studentsPayload} />
) : null}
</StudentsContainer>
);
};
const mapDispatchToProps = dispatch => ({ onClickButton: value => dispatch(fetchStudents(value)) });
const mapStateToProps = ({ students: { studentsPayload } }) => ({ studentsPayload });
/**
* Connects component to redux store
*/
const enhancer = connect(
mapStateToProps,
mapDispatchToProps,
)(Students);
export default enhancer;