Bil*_*dra 1 javascript reactjs react-native
我仍在学习 React Native,并且尝试从 API 检索数据并将其作为自定义单选按钮返回,但如果我确实调用 API,则会收到此错误:
null 不是对象(正在评估 'this.props.activities.map')
{this.props.activities.map((val, index) => {
let { key, type, placeholder } = val;
if (type === "selection") {
var buttons = [];
placeholder.forEach((e, index) => {
var selectedButton = img.findButton(e, true);
var normalButton = img.findButton(e);
buttons.push(
<RadioButton
key={index}
value={e}
element={<Image source={selectedButton} />}
selectedElement={<Image source={normalButton} />}
onPress={() => this.changeSelection(key, e)}
selected={this.state[key]["value"]}
/>
);
});
var rows = [],
columns = [];
var i = 0;
buttons.forEach((e, index) => {
rows.push(e);
i++;
if (i === 2 || index === buttons.length - 1) {
//max buttons per row
i = 0;
columns.push(
<View key={index} style={{ flex: 1, flexDirection: "row" }}>
{rows}
</View>
);
rows = [];
i = 0;
}
});
return (
<View key={key} style={{ flex: 1, margin: normalize(20) }}>
{columns}
</View>
);
}
})}Run Code Online (Sandbox Code Playgroud)
'this.props.activites' 来自于此
let initialState = {
activities: null,
};
export default function mainReducer(state = initialState, action) {
switch (action.type) {
case t.RECEIVE_ACT:
return Object.assign({}, state, { actReceived: true, activities: action.activities });
case t.EMPTY_ACT:
return Object.assign({}, state, { actReceived: false, activities: null });
default:
return state;
}
}Run Code Online (Sandbox Code Playgroud)
我想知道它是如何变成空的
的初始状态activities是null。因此,直到您从 api 收到响应之前,React 都会使用该值渲染这部分代码null。您可以指定activities: []为初始值,也可以在地图函数之前指定其是否为空,例如
{this.props.activities && this.props.activities.map((val, index) => {...
Run Code Online (Sandbox Code Playgroud)
如果您要使用activities: [],那么您仍然可以在地图之前进行检查,尽管它是可选的但仍然很好,例如;
{this.props.activities.length && this.props.activities.map((val, index) => {...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12020 次 |
| 最近记录: |