我正在尝试将动作创建者绑定到组件。
请找到以下代码段:
import { updateCities } from '../../redux/actions/home';
class Home extends React.Component {
constructor(props) {
super(props);
this.updateCities = updateCities.bind(this);
this.something = 'some value';
}
render() {
const { updateCities, home } = this.props;
return (
<div>
<div>
<input
onChange={e => {
const searchValue = e.target.value;
updateCities(searchValue);
}}
></input>
我的动作创建者:
export const updateCities = searchValue => async dispatch => {
console.log(this.something); // **undefined**
}
为什么结果不确定? 请帮忙。
答案 0 :(得分:0)
我想您可能需要使用HOC将操作连接到组件,
顺便说一下,有一个Microsoft最佳实践here
view.tsx
export const YourComponentExportName = connect( // <= here
(store: Store) => ({
inputStore: store.yourStore,
}),
(dispatch: any) => ({
yourRequest: (payload: requestParams) => dispatch(actionsWithService.yourRequest(payload)),
})
)(YourComponentClassName);
action.tsx
export const actionsWithService = {
yourRequest: (params: requestParams) => {
return async (dispatch: any, getState: () => Store) => {
const result = await service.yourRequest(params);
dispatch(actions.receieveResponse(result));
};
},
};
希望这会有所帮助
答案 1 :(得分:0)
首先,我假设您使用react-redux
的connect连接您的组件,因为在您发布的代码中看不到这一点。但是,如果您记录的是一个未定义的值,那么我假设您已连接了此组件,但是我必须将其发布以确保。
import { connect } from 'react-redux'
import { updateCities } from '../../redux/actions/home';
class Home extends React.Component {
// Your component
}
const mapStateToProps = state => ({
// your mapped state if you have one else put null where mapStateToProps is in your connect function
})
export default connect(mapStateToProps, {updateCities})(Home);
现在,这表示您没有将this.something
传递到updateCities函数。您具有以下条件:
export const updateCities = searchValue => async dispatch => {
console.log(this.something);
}
当您没有为其分配值并且没有将其传递给函数时,该函数如何知道this.something
。
如果要记录something值,则需要将其传递给函数并为其分配一个值,例如:
export const updateCities = something => async dispatch => {
console.log(something);
}
在组件中,您将this.something
传递到函数中,例如updateCities(this.something)
现在,如果您要执行的操作是记录searchValue,然后将searchvalue记录在updateCities函数中
export const updateCities = searchValue => async dispatch => {
console.log(searchValue);
}