我正在创建一个Web应用程序,其中用户在一个屏幕上选择一家餐馆,并存储了餐馆的名称,然后菜单屏幕检查了餐馆名称的状态,并从该餐馆的服务器获取菜单项。当我第一次按下cordova.plugins
中的按钮时,状态不会改变,但是下次会改变。但是,当我从userscreen.js
检查状态时,它仍然是初始化状态,为空。如何获取不更改为原始值的状态?
以下是我正在处理的文件:
userscreen.js
menu.js
menu.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setRestaurant } from '../actions/restaurant';
class Userscreen extends Component {
constructor(props){
super(props);
this.state={
r2:'',
};
this.handleClick1 = this.handleClick1.bind(this);
}
componentDidMount(){
fetch('api/rest-ratings', {
method: 'GET'
})
.then(res => res.json())
.then(body =>{
this.setState({r2: body.C})
})
}
handleClick1(event){
event.preventDefault()
this.props.setRestaurant("ChopChop");
console.log(this.props.rest)
}
render() {
return (
<div>
<img src={user_background} alt="" style= {{width: "100%", height: "auto", margin:"0auto"}}/>
<div id="btn2" onClick={this.handleClick1}>
Chop Chop
<div>
<StarRatingComponent name="ChopChop" editing={false} starCount={5} value={parseInt(this.state.r2)}/>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => ({
rest: state.rest,
})
export default connect(mapStateToProps, { setRestaurant })(Userscreen)
restaurant.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { setRestaurant } from '../actions/restaurant';
class Menu extends Component {
constructor(props){
super(props);
this.state={
rest1: 'abc',
};
}
componentDidMount(){
console.log("mine",this.state.rest1)
console.log("store",this.props.rest)
}
render() {
return (
<div>
{this.state.rest}
</div>
);
}
}
const mapStateToProps = (state) => ({
rest: state.rest
})
export default connect(mapStateToProps, {setRestaurant})(Menu);
restReducer.js
export const setRestaurant = (restaurant) => dispatch => {
dispatch({
type: 'SET_RESTAURANT',
payload: restaurant
})
}
index.js
const initialState = {
restaurant : ''
}
export default function(state = initialState, action ) {
switch(action.type) {
case 'SET_RESTAURANT':
return {
...state,
restaurant: action.payload,
}
default:
return state;
}
}
答案 0 :(得分:0)
如果要像在export default connect(mapStateToProps, {setRestaurant})(Menu);
中那样使用它,则应将您的调度绑定函数定义为一个简单的动作创建者:
export const setRestaurant = restaurant => ({
type: 'SET_RESTAURANT',
payload: restaurant
})
请参见defining mapDispatchToProps as an object
还请注意,mapStateToProps
函数通过 props 传递返回的对象(顾名思义),因此使用传递在props中的对象应该通过this.props
(相反) this.state
)。
return (
<div>{this.props.rest.restaurant}</div>
)