我有一个简单的React组件,我连接起来(映射一个简单的数组/状态).为了避免引用商店的上下文,我想要一种直接从道具中"调度"的方法.我见过其他人使用这种方法,但由于某种原因无法访问这个:)
以下是我目前正在使用的每个npm依赖项的版本
"react": "0.14.3",
"react-redux": "^4.0.0",
"react-router": "1.0.1",
"redux": "^3.0.4",
"redux-thunk": "^1.0.2"
Run Code Online (Sandbox Code Playgroud)
这是组件w/connect方法
class Users extends React.Component {
render() {
const { people } = this.props;
return (
<div>
<div>{this.props.children}</div>
<button onClick={() => { this.props.dispatch({type: ActionTypes.ADD_USER, id: 4}); }}>Add User</button>
</div>
);
}
};
function mapStateToProps(state) {
return { people: state.people };
}
export default connect(mapStateToProps, {
fetchUsers
})(Users);
Run Code Online (Sandbox Code Playgroud)
如果你需要看减速机(没有什么令人兴奋的,但在这里)
const initialState = {
people: []
};
export default function(state=initialState, action) {
if (action.type === ActionTypes.ADD_USER) {
let newPeople = …Run Code Online (Sandbox Code Playgroud) 我正在使用redux thunk来返回操作的API调用:
export const getActiveCampaigns = () => {
return (dispatch, getState) => {
const bearer = 'Bearer ' + getState().login.bearer
return axios.get(API.path + 'campaign/active/?website_id=' + getState().selectedWebsite.selectedWebsite + '&' + API.beaconAPI_client, { headers: { 'Authorization': bearer } })
.then(function (response) {
dispatch({
type: GET_ACTIVE_CAMPAIGNS,
activeCampaigns: response.data.response
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
这样做的原理是成功返回广告系列列表,我使用以下命令将其渲染到另一个组件中:
class ActiveCampaignsDropdown extends Component {
// usual stuff
componentDidMount(){
this.props.dispatch(getActiveCampaigns())
}
// render function displays campaigns using this.props.activeCampaigns
}
const mapStateToProps = (state) => {
return {
activeCampaigns: state.activeCampaigns.activeCampaigns …Run Code Online (Sandbox Code Playgroud)