【发布时间】:2018-07-03 18:01:57
【问题描述】:
在这里,我试图将状态从父组件/屏幕传递给子组件和孙子。起初,我尝试使用在 View 中声明的 Text 并且它可以工作,但是当我删除 中的 Text查看并在导航栏中声明它会给我一个错误。
而且,即使我只在 View 中用 Text 声明状态,从子代到孙子的状态也无法正常工作。(就像我在我的第一次)
这是我的代码
table.js (父级)
export default class tables extends Component {
state = {
data: [],
}
fetchData = async () => {
const response = await fetch("http://192.168.254.104:3308/table/");
const json = await response.json();
this.setState({ data: json })
}
componentDidMount() {
this.fetchData();
}
render() {
return (
<View>
<FlatList
....
renderItem = {({ item }) =>
<TouchableOpacity
onPress = { () => this.props.navigation.navigate('Category', { tbl: item.tbl_id })}>
<Text>{ item.tbl_id }</Text> // the data that will be pass.
</TouchableOpacity>
}
/>
</View>
)
}
}
Category.js (儿童)
export default class Category extends Component {
static navigationOptions = ({ navigation }) => (
{
headerLeft:
<Text>Table NO: { this.state.tbl }</Text> // navBar
}
);
constructor(props){
super(props)
this.state = {
data: [],
tbl: this.props.navigation.state.params.tbl,
};
}
render() {
return (
<View>
<Text>{ Table NO: { this.state.tbl }</Text> // But if I do it this way it's working fine.
<FlatList
....
renderItem = {({ item }) =>
<TouchableOpacity
onPress = { () => this.props.navigation.navigate('Dishes', { id: item.cat_id}, { tbl: item.tbl_id }) }>
<Text>{ item.cat_name }</Text>
</TouchableOpacity>
}
/>
</View>
)
}
}
Dishes.js (孙子)
export default class Dishes extends Component {
static navigationOptions = ({ navigation }) => (
{
headerLeft:
<Text>Table NO: { this.state.tbl }</Text> // navBar
}
);
constructor(props) {
super (props)
this.state = {
tbl: this.props.navigation.state.params.tbl,
}
}
render() {
return (
<View>
<Text>Table NO: { this.state.tbl }</Text> // In here, even if I do it this way it's not working. :-/
<FlatList
....
/>
</View>
)
}
}
【问题讨论】:
标签: javascript android reactjs react-native mobile